<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserve   .                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: liguohua@clcw.com.cn  Blog:http://blog.sina.com.cn/saverneo        |
// +------------------------------------------------------------------------+

namespace AuctionAppApi\Controller;

use AuctionCore\CarDealer\MyAuctioned;
use AuctionCore\Other\CouponList;
use AuctionCore\System\AuctionException;
use AuctionCore\CarDealer\BuyCarList;
use AuctionCore\CarResource\Car;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarResource\CarModel;
use AuctionCore\AuctionOrder\CarReturn;
use AuctionCore\AuctionOrder\AuOrderList;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\Finance\Collection;
use AuctionCore\Other\Inbox;
use AuctionCore\System\SystemConf;
use AuctionCore\Other\Address;
use AuctionCore\Common\PhpRedis;
use AuctionCore\Common\Util;
use AuctionCore\System\SystemLog;
use AuctionCore\Other\Raffle;
use AuctionCore\CarDealer\BidCarList;


/**
 * 交易管理接口
 */
class TradeController extends BaseController
{


    /**
     * 交易中心信息接口
     * @angl
     */
    public function index()
    {
        if ($this->dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        $bl = new BuyCarList($this->dealer_id);
        $data = array();
        $data['total_count'] = $bl->getCount(array('status' => 0));//待确认车辆个数
        $data['wait_confirm_count'] = $bl->getCount(array('status' => 1));//待确认车辆个数
        $data['wait_return_count'] = $bl->getCount(array('status' => 2));//成交待回车车辆个数
        $data['wait_check_count'] = $bl->getCount(array('status' => 3));//待验车车辆个数
        $data['wait_pay_count'] = $bl->getCount(array('status' => 4));//待付款车辆个数
        $data['paid_count'] = $bl->getCount(array('status' => 5));// 已付款车辆个数
        $data['success_count'] = $bl->getCount(array('status' => 6));//交易成功车辆个数
        $data['failure_count'] = $bl->getCount(array('status' => 7));//交易失败车辆个数
        $this->api_200($data);
    }

    /**
     * 买到的列表 客户端v1.1.1用接口
     * @author Eric
     */
    public function bought_list_v100($st=0)
    {
        $page = I('post.page/d', 1);
        $page_size = I('post.page_size/d', 20);
        $dealer_id = I('post.dealer_id/d', 0);
        $status = I('post.type/d', $st);
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        if ($status < 1) {
            AuctionException::make_throw('1000002');
        }
        $bl = new BuyCarList($dealer_id);
        //1:待确认、2:待付款、3:已付款、4:交易成功、5:交易失败 (旧）
        //1:待确认、2:成交待回车、3:待验车、4:待付款、5:已付款、6:交易成功、7:交易失败
        if(I('post.type/d')){
            switch(I('post.type/d')){
                case '2':$status=4;break;
                case '3':$status=5;break;
                case '4':$status=6;break;
                case '5':$status=7;break;
            }
        }

        $std_arr = [1 => "待确认", 2 => "成交待回车", 3 => "待验车", 4 => "待付款", 5 => "已付款", 6 => "交易成功", 7 => "交易失败"];
        if (!array_key_exists($status, $std_arr)) {
            AuctionException::make_throw('500014');
        }
        $params = array('status' => $status);
        $result = $bl->getList($page, $page_size, $params);
        $list = empty($result['list']) ? array() : $result['list'];
        $total = empty($result['total']) ? 0 : $result['total'];
        $bought_list = array();
        foreach ($list as $k => $val) {
            $bought_list[$k]['order_id'] = $val['order_id'];

            $img = Car::get_pic_by_key($val['car_id'], "p_left_front45");//左前45°图片
            $bought_list[$k]['img'] = $img['pic_url'];

            $bought_list[$k]['composite_level'] = $val['composite_state'].$val['accident_level'];
            $bought_list[$k]['car_name'] = $val['model'];

            $transfer_limit = C('TRANSFER_LIMIT.' . $val['transfer_limit']);
            $bought_list[$k]['desc'] = $val['order_no'].'/'.$transfer_limit.'/上门自提' ;
            $bought_list[$k]['trade_time'] = date('Y-m-d H:i',strtotime($val['bidding_end_time']));

        }
        $data = array(
            'currentpage' => $page,
            'pagesize' => $page_size,
            'maxcount' => $total,
            'maxpage' => ceil($total / $page_size),
            'list' => $bought_list
        );
        $this->api_200($data);
    }

    /**
     * 待回车列表
     */
    public function return_list(){
        $this->bought_list_v100(2);
    }


    /**
     * 待验车列表
     */
    public function wait_check_list(){
        $this->bought_list_v100(3);
    }


    /**
     * 买到的列表
     * @author angl
     */
    public function bought_list()
    {
        $page = I('post.page/d', 1);
        $page_size = I('post.page_size/d', 20);
        $dealer_id = I('post.dealer_id/d', 0);
        $status = I('post.type/d', 0);
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        if ($status < 1) {
            AuctionException::make_throw('1000002');
        }
        $bl = new BuyCarList($dealer_id);
        //1:待确认、2:待付款、3:已付款、4:交易成功、5:交易失败
        $std_arr = [1 => "待确认", 2 => "待付款", 3 => "已付款", 4 => "交易成功", 5 => "交易失败"];
        if (!array_key_exists($status, $std_arr)) {
            AuctionException::make_throw('500014');
        }
        $params = array('status' => $status);
        $result = $bl->getList($page, $page_size, $params);
        $list = empty($result['list']) ? array() : $result['list'];
        $total = empty($result['total']) ? 0 : $result['total'];
        $bought_list = array();
        foreach ($list as $k => $val) {
            $bought_list[$k]['order_id'] = $val['order_id'];

            $img = Car::get_pic_by_key($val['car_id'], "p_left_front45");//左前45°图片
            $bought_list[$k]['img'] = $img['pic_url'];

            $bought_list[$k]['composite_level'] = $val['composite_state'].$val['accident_level'];
            $bought_list[$k]['car_name'] = $val['model'];

            $transfer_limit = C('TRANSFER_LIMIT.' . $val['transfer_limit']);
            $bought_list[$k]['desc'] = $val['order_no'].'/'.$transfer_limit.'/上门自提' ;
            $bought_list[$k]['trade_time'] = date('Y-m-d H:i',strtotime($val['bidding_end_time']));

        }
        $data = array(
            'currentpage' => $page,
            'pagesize' => $page_size,
            'maxcount' => $total,
            'maxpage' => ceil($total / $page_size),
            'list' => $bought_list
        );
        $this->api_200($data);
    }

    /**
     * 仲裁列表
     */
    public function arbitrate_list(){
        $page = I('post.page/d', 1);
        $page_size = I('post.page_size/d', 20);

        $dealer_id = I('post.dealer_id/d', 0);
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        $type = I('post.type/d', 0);//1 待仲裁 2已仲裁
        if ($type < 1) {
            AuctionException::make_throw('1000002');
        }

        $bl = new BuyCarList($dealer_id);
        $result = $bl->get_arbitrate_list($page, $page_size, $dealer_id,$type);
        $list = empty($result['list']) ? array() : $result['list'];
        $total = empty($result['total']) ? 0 : $result['total'];

        $data = array(
            'currentpage' => $page,
            'pagesize' => $page_size,
            'maxcount' => $total,
            'maxpage' => ceil($total / $page_size),
            'list' => $list
        );

        $this->api_200($data);
    }

    /**
     * 仲裁详情
     */
    public function arbitrate_detail(){

        $issue_id = I('post.order_id/d', 0);
        $dealer_id = I('post.dealer_id/d', $this->dealer_id);
        if ($issue_id < 1) {
            AuctionException::make_throw('700092');
        }
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        $order_id = AuOrder::get_order_id_by_issue_id($issue_id);
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }
        //拍单基本信息
        $o = new AuOrder($order_id);
        $order_info = $o->detail();

        //争议基本信息
        $issue_info = $o->get_issue_detail($issue_id);
        //车辆基本信息
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();

        //验车信息
        $d = new MyAuctioned($dealer_id);
        //$check_info = $d->get_check_detail($order_id);

        //车型
        $cm = new CarModel();
        $a = new Address();
        $city_name = $a->get_name_by_code($car_info['location_area']);
        $series = $cm->get_model_by_id($car_info['series_id'], 'series');
        $car_model = '['.$city_name.'] '.$series['name'] . ' ' . $car_info['car_cc'] . ($car_info['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_info['gearbox']);

        //数据整理
        $data = array();
        $data['car_id'] = $order_info['car_id'];

        $data['base_info']['order_id'] = $order_info['order_id'];

        $img = Car::get_pic_by_key($car_info['car_id'], "p_left_front45");//左前45°图片
        $data['base_info']['img'] = $img['pic_url'];

        $data['base_info']['composite_level'] = $car_info['composite_state'].$car_info['accident_level'];
        $data['base_info']['car_name'] = $car_model;

        $transfer_limit = C('TRANSFER_LIMIT.' . $car_info['transfer_limit']);
        $data['base_info']['desc'] = $order_info['order_no'].'/'.$transfer_limit.'/上门自提' ;
        $data['base_info']['trade_time'] = date('Y-m-d H:i',strtotime($order_info['bidding_end_time']));

        //仲裁信息
        //原因及处理结果
        $issue_reason = '/';
        $deal_result = '/';
        switch($issue_info['issue_type']){

            case '1'://车况不符
                $issue_reason = '车况不符';
                if($issue_info['status']==1){
                    $deal_result = '协商成功，交易继续。';
                }elseif($issue_info['status']==2){//车商违约
                    $deal_result = '扣除违约金，交易失败。';
                }elseif($issue_info['status']==3){//我方违约
                    $deal_result = '协商补偿，交易失败。';
                }
            break;
            case '2'://超时验车
                $issue_reason = '超时验车';
                if($issue_info['status']==1){
                    $deal_result = '协商成功，交易继续。';
                }elseif($issue_info['status']==2){//车商违约
                    $deal_result = '扣除违约金，交易失败。';
                }elseif($issue_info['status']==3){//我方违约
                    $deal_result = '协商补偿，交易失败。';
                }
                break;
            case '3'://待过户争议
                $issue_reason = '待过户争议';
                if($issue_info['status']==1){
                    $deal_result = '协商成功，交易继续。';
                }elseif($issue_info['status']==2){//车商违约
                    $deal_result = '扣除违约金，交易失败。';
                }elseif($issue_info['status']==3){//我方违约
                    $deal_result = '协商补偿，交易失败。';
                }
                break;
            case '4'://付款超时
                $issue_reason = '结算争议';
                if($issue_info['status']==1){
                    $deal_result = '协商成功，交易继续。';
                }elseif($issue_info['status']==2){//车商违约
                    $deal_result = '扣除违约金，交易失败。';
                }elseif($issue_info['status']==3){//我方违约
                    $deal_result = '协商补偿，交易失败。';
                }
                break;
            case '5'://过户中争议
                $issue_reason = '过户中争议';
                if($issue_info['status']==1){
                    $deal_result = '协商成功，交易继续。';
                }elseif($issue_info['status']==2){//车商违约
                    $deal_result = '扣除违约金，交易失败。';
                }elseif($issue_info['status']==3){//我方违约
                    $deal_result = '协商补偿，交易失败。';
                }
                break;
            case '6'://待收款争议
                $issue_reason = '待收款争议';
                if($issue_info['status']==1){
                    $deal_result = '协商成功，交易继续。';
                }elseif($issue_info['status']==2){//车商违约
                    $deal_result = '扣除违约金，交易失败。';
                }elseif($issue_info['status']==3){//我方违约
                    $deal_result = '协商补偿，交易失败。';
                }
                break;
            case '7'://核实收款争议
                $issue_reason = '核实收款争议';
                if($issue_info['status']==1){
                    $deal_result = '协商成功，交易继续。';
                }elseif($issue_info['status']==2){//车商违约
                    $deal_result = '扣除违约金，交易失败。';
                }elseif($issue_info['status']==3){//我方违约
                    $deal_result = '协商补偿，交易失败。';
                }
                break;

        }
        $data['arbitrate'] = array();
        $data['arbitrate']['info'] = array(
                                        array('name'=>'仲裁原因','value'=>$issue_reason),
                                        array('name'=>'仲裁描述','value'=>$issue_reason),
                                        array('name'=>'申请时间','value'=>$issue_info['createtime']),//申请时间
                                    );
        if($issue_info['status']>0){
            $data['arbitrate']['result'][] = array('name'=>'仲裁结果','value'=>$deal_result);
            $data['arbitrate']['result'][] = array('name'=>in_array($issue_info['status'],array(1,3))?'补偿金额':($issue_info['status']==2?'扣除金额':''),'value'=>$issue_info['cut_down_price'].'元');//发生金额
            $data['arbitrate']['result'][] = array('name'=>'仲裁时间','value'=>$issue_info['updatetime']);//仲裁时间
        }

        $this->api_200($data);

    }


    /**
     * 交易拍单详情  客户端v1.1.1版本用接口
     * @author lc
     */
    public function order_detail_v100()
    {
        $order_id = I('post.order_id/d', 0);
        $dealer_id = I('post.dealer_id/d', $this->dealer_id);
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        $o = new AuOrder($order_id);
        $d = new MyAuctioned($this->dealer_id);
        $order_info = $o->detail();
        $auctioned = $d->get_by_order_id($order_id);
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();
        $cm = new CarModel();
        $a = new Address();
        $city_name = $a->get_name_by_code($car_info['location_area']);
        $series = $cm->get_model_by_id($car_info['series_id'], 'series');
        $car_model = '['.$city_name.'] '.$series['name'] . ' ' . $car_info['car_cc'] . ($car_info['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_info['gearbox']);
        $data = array();
        $data['car_id'] = $order_info['car_id'];
        $data['base_info'] = [
            ['name' => "拍单号", "value" => $order_info['order_no']],
            ['name' => "车型", "value" => $car_model],
            ['name' => "成交时间", "value" => $order_info['bidding_end_time']],
            ['name' => "过户限制", "value" => C('TRANSFER_LIMIT.' . $car_info['transfer_limit'])],
            ['name' => "提车方式", "value" => C('TAKE_METHOD.' . $auctioned['take_method'])]
        ];

        $data['order_coupon'] = intval($order_info['coupon']);

        //计算优惠券
        //代金券
        $Coupon = new CouponList();
        $coupon_money = $Coupon->getSumCouponCost($dealer_id, $order_id);
        $data['coupon'] = $coupon_money > $order_info['coupon'] ? intval($order_info['coupon']) : intval($coupon_money);

        //抽奖
        $lottery = new Raffle();
        $arr = $lottery->find_card_activity($order_id,1);//取出已抽奖的信息
        $data['lottery'] = !empty($arr)?intval($arr[0]['price']):0;

        //优惠信息（满足代金券使用条件方可显示代金券信息）
        //代金券和抽奖入口(只用待车商付款和符合抽奖条件时展示）
        if($order_info['status']==8 && $order_info['dealer_pay_status']==1){
            if($data['coupon']<=0){//已用的总额为零，则查可用多少
                $coupon_available = $Coupon->getSumCouponAvailable($dealer_id);
                $coupon_available = $coupon_available > $order_info['coupon'] ? $order_info['coupon'] : $coupon_available;
            }
            $data['discount']['coupon'] = array(
                                            'is_usable'=>true,
                                            'is_used'=>($data['coupon']>0?true:false),
                                            'desc'=>($data['coupon']>0?'-'.$data['coupon'].'元':'可用'.intval($coupon_available).'元')
                                        );
            //车商确认后方可显示抽奖信息
            $data['discount']['lottery'] = array(
                                                'is_usable'=>($arr?true:false),
                                                'is_used'=>($arr[0]['state']>0?true:false),
                                                'desc'=>($arr[0]['use_state']<=0 && $arr[0]['state']>0?'-'.$data['lottery'].'元':'去抽奖'),
                                                'url'=>($arr?APP_URL.'Raffle/raffle/type/1/order_id/'.$order_id:'')
                                            );
        }else{
            //代金券
            $data['discount']['coupon'] = array('is_usable' => false);
            //抽奖
            $data['discount']['lottery'] = array('is_usable' => false);
        }

        $Raffle = $arr[0]['state']>0?$data['lottery']:0;
        //应付总额

        $should_pay = $auctioned['trade_price'] + $order_info['commision'] + $order_info['transfer_fee'] - $data['coupon'] - $Raffle - $order_info['compensation'];

        $data['cost'] = array(
            array('name' => '拍卖最高价', 'value' => (int)$auctioned['trade_price'] . " 元"),
        );
        if ($order_info['commision'] > 0) {
            $data['cost'][] = array('name' => '交易服务费', 'value' => "+ " . (int)$order_info['commision'] . " 元");
        }
        if ($order_info['transfer_fee'] > 0) {
            $data['cost'][] = array('name' => '交付服务费', 'value' => "+ " . (int)$order_info['transfer_fee'] . " 元");
        }

        if ($order_info['compensation'] > 0) {
            $data['cost'][] = array('name' => '仲裁补偿', 'value' => "- " . (int)$order_info['compensation'] . " 元");
        }

        if ($data['coupon'] > 0) {
            $data['cost'][] = array('name' => '代金券', 'value' => "- " . (int)$data['coupon'] . " 元");
        }
        if ($arr[0]['state']>0 && $data['lottery'] > 0) {
            $data['cost'][] = array('name' => '抽奖立减', 'value' => "- " . (int)$data['lottery'] . " 元");
        }
        $data['should_pay'] = (int)$should_pay . " 元";
        //订单生成、已付款、已过户、提车完成、交易完成
        $process = array();
        $data['process'] = $process;
        $this->api_200($data);
    }

    /**
     * 交易拍单详情
     * @author angl
     */
    public function order_detail()
    {
        $order_id = I('post.order_id/d', 0);
        $dealer_id = I('post.dealer_id/d', 0);
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        $o = new AuOrder($order_id);
        $d = new MyAuctioned($this->dealer_id);
        $order_info = $o->detail();
        $auctioned = $d->get_by_order_id($order_id);
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();
        $cm = new CarModel();
        $series = $cm->get_model_by_id($car_info['series_id'], 'series');
        $car_model = $series['name'] . ' ' . $car_info['car_cc'] . ($car_info['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_info['gearbox']);
        $data = array();
        $data['car_id'] = $order_info['car_id'];
        $data['base_info'] = [
            ['name' => "拍单号", "value" => $order_info['order_no']],
            ['name' => "车型", "value" => $car_model],
            ['name' => "成交时间", "value" => $order_info['bidding_end_time']],
            ['name' => "过户限制", "value" => C('TRANSFER_LIMIT.' . $car_info['transfer_limit'])],
            ['name' => "提车方式", "value" => C('TAKE_METHOD.' . $auctioned['take_method'])]
        ];

        //计算优惠券
        //代金券
        $Coupon = new CouponList();
        $coupon_money = $Coupon->getSumCouponCost($dealer_id, $order_id);
        $data['coupon'] = $coupon_money > $order_info['coupon'] ? intval($order_info['coupon']) : intval($coupon_money);

        //抽奖
        $lottery = new Raffle();
        $arr = $lottery->find_card_activity($order_id,1);//取出已抽奖的信息
        $data['lottery'] = !empty($arr)?intval($arr[0]['price']):0;

        //优惠信息（满足代金券使用条件方可显示代金券信息）
        //代金券和抽奖入口(只用待车商付款和符合抽奖条件时展示）
        if($order_info['status']==8 && $order_info['dealer_pay_status']==1){
            if($data['coupon']<=0){//已用的总额为零，则查可用多少
                $coupon_available = $Coupon->getSumCouponAvailable($dealer_id);
                $coupon_available = $coupon_available > $order_info['coupon'] ? $order_info['coupon'] : $coupon_available;
            }
            $data['discount']['coupon'] = array(
                                            'is_usable'=>true,
                                            'is_used'=>($data['coupon']>0?true:false),
                                            'desc'=>($data['coupon']>0?'-'.$data['coupon'].'元':'可用'.intval($coupon_available).'元')
                                        );
            //车商确认后方可显示抽奖信息
            $data['discount']['lottery'] = array(
                                                'is_usable'=>($arr?true:false),
                                                'is_used'=>($arr[0]['state']>0?true:false),
                                                'desc'=>($arr[0]['use_state']<=0 && $arr[0]['state']>0?'-'.$data['lottery'].'元':'去抽奖'),
                                                'url'=>($arr?APP_URL.'Raffle/raffle/type/1/order_id/'.$order_id:'')
                                            );
        }else{
            //代金券
            $data['discount']['coupon'] = array('is_usable' => false);
            //抽奖
            $data['discount']['lottery'] = array('is_usable' => false);
        }

        $Raffle = $arr[0]['state']>0?$data['lottery']:0;
        //应付总额
        $should_pay = $auctioned['trade_price'] + $order_info['commision'] + $order_info['transfer_fee'] - $data['coupon']-$Raffle;
        $label = '';
        if($order_info['consult_increase'] > 0){
            $label = "(磋商)";
        }
        $data['cost'] = array(
            array('name' => '拍卖最高价'.$label, 'value' => (int)$auctioned['trade_price'] . " 元"),
        );
        if ($order_info['commision'] > 0) {
            $data['cost'][] = array('name' => '交易服务费', 'value' => "+ " . (int)$order_info['commision'] . " 元");
        }
        if ($order_info['transfer_fee'] > 0) {
            $data['cost'][] = array('name' => '交付服务费', 'value' => "+ " . (int)$order_info['transfer_fee'] . " 元");
        }
        if ($data['coupon'] > 0) {
            $data['cost'][] = array('name' => '代金券', 'value' => "- " . (int)$data['coupon'] . " 元");
        }
        if ($arr[0]['state']>0 && $data['lottery'] > 0) {
            $data['cost'][] = array('name' => '抽奖立减', 'value' => "- " . (int)$data['lottery'] . " 元");
        }
        $data['should_pay'] = (int)$should_pay . " 元";
        //订单生成、已付款、已过户、提车完成、交易完成
        $process = array();
        $data['process'] = $process;
        $this->api_200($data);
    }

    /**
     * 我出价的拍单列表
     * @author Eric Lee
     */
    public function bid_price_list()
    {
        //
        $page = I('post.page', '1');
        $page_size = I('post.page_size', '20');
        $dealer_id = $this->dealer_id;

        $list = new BidCarList($dealer_id);
        $total = $list->count();
        $bl = new BuyCarList($dealer_id);
        $ret = $list->get($page_size, $page);
        $trade_status = [
            '8' => "待付款",
            '9' => "待过户",
            '10' => "待过户",
            '11' => "交易成功",
            '13' => "交易成功"
        ];
        $list = array();
        foreach ($ret as $key => $value) {
            $list[$key]['car_id'] = $value['car_id'];
            $list[$key]['order_id'] = $value['order_id'];
            $list[$key]['order_no'] = $value['order_no'];
            $list[$key]['state'] = $value['success_price'] >= $value['reserve_price'] ? '5' : '6';
            $list[$key]['car_name'] = $value['model_info'];
            $list[$key]['trade_time'] = $value['bidding_end_time'];
            $label = '';
            if($value['consult_increase'] > 0){
                $label = "磋商";
            }
            if ($value['bid_best_price'] >= $value['bidding_best_price']) {
                $success_price = $value['bid_best_price'];
                $method = "元（".$label."投标）";
            } else {
                $success_price = $value['bidding_best_price'];
                $method = "元（".$label."竞拍）";
            }
            $list[$key]['top_price'] = strip_tags(format_money($success_price)) . $method;
            //我最后的投标价
            $bid = M('bid_log')->where("order_id='" . $value['order_id'] . "' AND dealer_id='" . $dealer_id . "'")->order("createtime DESC")->find();
            $value['my_last_bid_price'] = $bid['price'];
            //最高竞标价
            $bidding = M('bidding_log')->field("MAX(after_price) maxprice")->where("order_id='" . $value['order_id'] . "' AND dealer_id='" . $dealer_id . "'")->find();
            $value['my_max_bidding_price'] = $bidding['maxprice'];
            $list[$key]['my_bid'] = $value['my_last_bid_price'] > 0 ? strip_tags(format_money($value['my_last_bid_price'])) . '元' : '未投标';
            $list[$key]['is_top_bid'] = $value['bid_best_price'] == $value['my_last_bid_price'] ? true : false;
            $list[$key]['my_bidding'] = $value['my_max_bidding_price'] > 0 ? strip_tags(format_money($value['my_max_bidding_price'])) . '元' : '未竞拍';
            $list[$key]['is_top_bidding'] = $value['bidding_best_price'] == $value['my_max_bidding_price'] ? true : false;

            if ($success_price >= $value['reserve_price']) {
                $result = $value['success_dealer_id'] == $dealer_id ? '2' : '1';
            } else {
                $result = '1';
            }
            $list[$key]['result'] = $result;
            $img = Car::get_pic_by_key($value['car_id'], "p_left_front45");//左前45°图片
            $list[$key]['img'] = $img['pic_url'];

            $list[$key]['state_name'] = BuyCarList::get_bid_status($value);
            $list[$key]['result_name'] = $bl->is_get_status($value);
            $list[$key]['state_color'] = 2;
        }
        $data = array();
        $data['currentpage'] = $page;
        $data['pagesize'] = $page_size;
        $data['maxcount'] = $total;
        $data['maxpage'] = ceil($total/$page_size);
        $data['list'] = $list;
        $this->api_200($data);
    }

    /**
     * 交易详情页  客户端v1.2.0版本用接口
     * @author luchao   16-07-21
     */
    public function order_detail_v120(){
        $order_id = I('post.order_id/d', 0);
        $dealer_id = I('post.dealer_id/d', $this->dealer_id);
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        $o = new AuOrder($order_id);
        $order_info = $o->detail();
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();
        $cm = new CarModel();
        $a = new Address();
        $city_name = $a->get_name_by_code($car_info['location_area']);
        $series = $cm->get_model_by_id($car_info['series_id'], 'series');
        $car_model = '['.$city_name.'] '.$series['name'] . ' ' . $car_info['car_cc'] . ($car_info['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_info['gearbox']);
        $img = Car::get_pic_by_key($order_info['car_id'], "p_left_front45");//左前45°图片 
        $data = array();
        $data['content'][] = array(
                "type"=>"header",
                "car_name"=>$car_model,
                "img"=>$img['pic_url'],
                "summary"=>$order_info['order_no']."/".C('TRANSFER_LIMIT.' . $car_info['transfer_limit'])."/".C('TAKE_METHOD.' . 1)
            );

        $items = array();
        //代金券
        $Coupon = new CouponList();
        $coupon_money = $Coupon->getSumCouponCost($dealer_id, $order_id);
        if ($coupon_money) {
            $used_coupon = $coupon_money > $order_info['coupon'] ? $order_info['coupon'] : $coupon_money;
            $items[] = array("type"=>"name_value","name"=>"代金券","value"=>"-".(int)$used_coupon. " 元");
        }
        //抽奖
        $lottery = new Raffle();
        $arr = $lottery->find_card_activity($order_id,1);//取出已抽奖的信息
        if ($arr['state']>0) {
            $raffle = $arr['price'];
            $items[] = array("type"=>"name_value","name"=>"抽奖立减","value"=>"-".(int)$raffle. " 元");
        }
        if ($order_info['transfer_type'] == 1) {
            $order_info['transfer_fee'] = 0;
        }
        $order_info['success_price'] = $order_info['bidding_best_price'] > $order_info['bid_best_price'] ? $order_info['bidding_best_price'] : $order_info['bid_best_price'];
        $bl = new BuyCarList($this->dealer_id);
        //场次活动
        $res_activity = $bl->is_scene_activity($order_info['scene_id']);
        if(!empty($res_activity)){
            //根据场次活动减免规则id找到减免规则
            foreach($res_activity as $k => $v){
                if($v['rules_type'] == 2){ //如果减免规则的rules_type == 2 说明是阶梯立减 去activity_rules表中找到相应的详细规则
                    $scene_activity_amount = $bl->get_activity_rules_price($v['scene_activity_id'],$order_info['success_price']);
                    $items[] = array("type"=>"name_value","name"=>"活动立减","value"=>"-".(int)$scene_activity_amount. " 元");
                }else if($v['rules_type'] == 1){ //如果减免规则rules_type == 1 说明是活动统一立减,取出scene_activity['amount'] 即可
                    $scene_activity_amount = $v['amount'];
                    $items[] = array("type"=>"name_value","name"=>"活动立减","value"=>"-".(int)$scene_activity_amount. " 元");
                }
            }
        }else{
            $scene_activity_amount = 0; //判断如果没有活动减免价格 则设置scene_activity_amount的值为0;
        }
        if ($raffle || $used_coupon || $res_activity) {
            $data['content'][] = array(
                "type"=>"group",
                "title"=>"优惠信息",
                "items"=>$items
            );
        }
        //应付总款
         $should_pay = $order_info['success_price'] + $order_info['commision'] + $order_info['transfer_fee'] - $used_coupon - $raffle - $order_info['compensation'] - $scene_activity_amount;
        $data['content'][0]['should_pay'] = "应付总款：".(int)$should_pay. " 元";

        //支付信息
        $items1 = array();
        $label = '';
        if($order_info['consult_increase'] > 0){
            $label = "(磋商)";
        }
        $items1[] = array('type'=>'name_value','name' => '拍卖最高价'.$label, 'value' => (int)$order_info['success_price'] . " 元");
        if ($order_info['commision'] > 0) {
           $items1[] = array('type'=>'name_value' ,'name' => '交易服务费', 'value' => "+ " . (int)$order_info['commision'] . " 元");
        }
        if ($order_info['transfer_fee'] > 0 && $order_info['transfer_type'] != 1) {
        // if ($order_info['transfer_fee'] > 0 && $order_info['transfer_type'] != 1) {
            $items1[] = array('type'=>'name_value' ,'name' => '交付服务费', 'value' => "+ " . (int)$order_info['transfer_fee'] . " 元");
        }

        //车商补偿
        $map = [];
        $map['dc.order_id'] = $order_id;
        $map['dc.status'] = [['eq',1],['eq',2],'or'];
        if($order_info['compensation'] > 0){  //先验车后付款
            $should_pay = $should_pay - $order_info['compensation'];
            $items1[] = array('type'=>'name_value' ,'name' => '验车补偿', 'value' => "- " . (int)$order_info['compensation'] . " 元");
        }
        // $compensations = M("dealer_compensate")->alias("dc")->field("dc.compensate_amount,di.issue_type")
        //     ->join(C("DB_PREFIX")."dealer_issue as di ON di.issue_id=dc.issue_id")
        //     ->where($map)->select();

        // if(!empty($compensations)){
        //     foreach ($compensations as $k=>$val){
        //         switch ($val['issue_type']){
        //             case 1:
        //                 $should_pay = $should_pay - $val['compensate_amount'];
        //                 $items1[] = array('type'=>'name_value' ,'name' => '验车补偿', 'value' => "- " . (int)$val['compensate_amount'] . " 元");
        //                 break;
        //             case 3:
        //                 $should_pay = $should_pay - $val['compensate_amount'];
        //                 $items1[] = array('type'=>'name_value' ,'name' => '过户前补偿', 'value' => "- " . (int)$val['compensate_amount'] . " 元");
        //                 break;
        //             case 5:
        //                 $should_pay = $should_pay - $val['compensate_amount'];
        //                 $items1[] = array('type'=>'name_value' ,'name' => '过户中补偿', 'value' => "- " . (int)$val['compensate_amount'] . " 元");
        //                 break;
        //         }
        //     }
        // }
        if ($used_coupon) {
            $items1[] = array('type'=>'name_value' ,'name' => '代金券', 'value' => "- " . (int)$used_coupon . " 元");
        }
        if ($raffle) {
            $items1[] = array('type'=>'name_value' ,'name' => '抽奖立减', 'value' => "- " . (int)$raffle . " 元");
        }
        if(!empty($res_activity)){
            $items1[] = array('type' => 'name_value', 'name' => "活动减免 ",'value'=>"- ". (int)$scene_activity_amount . " 元");
        }
        $data['content'][0]['should_pay'] = "应付总款：".(int)$should_pay. " 元";
        $items1[] = array('type'=>'total_pay' ,'name' => '应付总款', 'value' =>  (int)$should_pay . " 元");
        if (!empty( $items1)) {
             $data['content'][] = array(
                "type"=>"group",
                "title"=>"支付信息",
                "items"=>$items1
                );
        }
        //抽奖信息
        $items2 = array();
        $Dealer = new Dealer($dealer_id);
        $raffle_coupon = $Dealer->get_raffle_coupon($order_id,2);
        if ($raffle_coupon) {
            foreach ($raffle_coupon as $key => $value) {
                $items2[] = array(
                    'type'=>'name_value',
                    'name'=>"代金券：".$value['coupon_no'],
                    'value'=>$value['amount']
                    );
            }
           $data['content'][]= array(
                "type"=>"group",
                "title"=>"抽奖信息",
                "items"=>$items2
            );
        }
        //付款信息
        $items3 = array();
        if ($order_info['is_self_confirm'] == 1) {
            $map1 = array();
            $map1['order_id'] = $order_id;
            $loan_log = M('loan_log')->where($map1)->find();
            if (empty($loan_log)) {
                if ($order_info['dealer_pay_status'] == 3) {
                    $items3[] = array('type'=>'name_value','name'=>"全款",'value'=>$should_pay."(已支付)");
                }elseif(in_array($order_info['dealer_pay_status'], array(1,2)) && $order_info['status'] != 12){
                    $items3[] = array('type'=>'name_value','name'=>"全款",'value'=>$should_pay."(待支付)");
                }elseif($order_info['status'] == 12 && $order_info['dealer_pay_status'] == 5){
                    $items3[] = array('type'=>'name_value','name'=>"全款",'value'=>$should_pay."(支付失败)");
                }elseif($order_info['dealer_pay_status'] == 4){
                    $items3[] = array('type'=>'name_value','name'=>"全款",'value'=>$should_pay."(支付锁定)");
                }
            }else{
                $first_pay_money = $loan_log['first_pay_money'];
                $loan_money = $loan_log['loan_money'];
                $loan_status = $loan_log['loan_status'];
                if ($first_pay_money == 0) {
                    $items3[] = array('type'=>'name_value','name'=>"贷款",'value'=>$loan_money."(已支付)");
                }else{
                    if ($loan_status == 1) {
                        if ($order_info['dealer_pay_status'] == 3) {
                            $items3[] = array('type'=>'name_value','name'=>"首付",'value'=>$first_pay_money."(已支付)");
                            $items3[] = array('type'=>'name_value','name'=>"贷款",'value'=>$loan_money."(已支付)");
                        }elseif ($order_info['dealer_pay_status'] < 3  && $order_info['status'] != 12) {
                            $items3[] = array('type'=>'name_value','name'=>"首付",'value'=>$first_pay_money."(待支付)");
                            $items3[] = array('type'=>'name_value','name'=>"贷款",'value'=>$loan_money."(待支付)");
                        }elseif ($order_info['status'] == 12 && $order_info['dealer_pay_status'] == 5) {
                            $items3[] = array('type'=>'name_value','name'=>"首付",'value'=>$first_pay_money."(支付失败)");
                            $items3[] = array('type'=>'name_value','name'=>"贷款",'value'=>$loan_money."(支付失败)");
                        }elseif ($order_info['dealer_pay_status'] == 4) {
                            $items3[] = array('type'=>'name_value','name'=>"首付",'value'=>$first_pay_money."(支付锁定)");
                            $items3[] = array('type'=>'name_value','name'=>"贷款",'value'=>$loan_money."(支付锁定)");
                        }
                    }else{
                        $items3[] = array('type'=>'name_value','name'=>"首付",'value'=>$first_pay_money."(已支付)");
                        $items3[] = array('type'=>'name_value','name'=>"贷款",'value'=>$loan_money."(已支付)");
                    }
                }
            }
            $data['content'][]= array(
                "type"=>"group",
                "title"=>"付款信息",
                "items"=>$items3
            );
        }
        $car_id = $order_info['car_id'];
        if ($car_id) {
            $data['content'][]= array(
                "type"=>"report",
                "title"=>"检测报告",
                "car_id"=>$car_id
            );
        }

        $this->api_200($data);

    }


    /**
     * 车辆结算页  客户端v1.2.0版本用接口
     * @author luchao 16-07-21
     */
    public function car_statement_v120(){
        $order_id = I('post.order_id/d', 0);
        $dealer_id = I('post.dealer_id/d', $this->dealer_id);
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        $o = new AuOrder($order_id);
        $d = new MyAuctioned($this->dealer_id);
        $order_info = $o->detail();
        $auctioned = $d->get_by_order_id($order_id);
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();
        $cm = new CarModel();
        $a = new Address();
        $city_name = $a->get_name_by_code($car_info['location_area']);
        $series = $cm->get_model_by_id($car_info['series_id'], 'series');
        $car_model = '['.$city_name.'] '.$series['name'] . ' ' . $car_info['car_cc'] . ($car_info['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_info['gearbox']);
        $img = Car::get_pic_by_key($order_info['car_id'], "p_left_front45");//左前45°图片 
        $data = array();
        $data['content'][] = array(
                "type"=>"header",
                "car_name"=>$car_model,
                "img"=>$img['pic_url'],
                "summary"=>$order_info['order_no']."/".C('TRANSFER_LIMIT.' . $car_info['transfer_limit'])."/".C('TAKE_METHOD.' . $auctioned['take_method'])
            );

        $items = array();
        //代金券
        $Coupon = new CouponList();
        $coupon_money = $Coupon->getSumCouponCost($dealer_id, $order_id);
        if ($coupon_money) {
            $used_coupon = $coupon_money > $order_info['coupon'] ? $order_info['coupon'] : $coupon_money;
            $items[] = array("type"=>"name_value","name"=>"代金券","value"=>"-".(int)$used_coupon. " 元");
        }elseif (!$coupon_money && $order_info['coupon']>0 ) {
            $items[] = array("type"=>"coupon","name"=>"代金券","value"=>"可用".$order_info['coupon']. " 元","order_coupon"=>(int)$order_info['coupon']);
        }
        //抽奖
        $lottery = new Raffle();
        $arr = $lottery->find_card_activity($order_id,1);//取出已抽奖的信息
        if ($arr['state']>0) {
            $raffle = $arr['price'];
            $items[] = array("type"=>"name_value","name"=>"抽奖立减","value"=>"-".(int)$raffle. " 元");
        }elseif ($arr && $arr['state']==0 ){
            $items[] = array("type"=>"activity","name"=>"抽奖立减","value"=>"去抽奖","url"=>APP_URL.'Raffle/raffle/type/1/order_id/'.$order_id,"title"=>"抽奖");
        }
        if (
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && $order_info['check_car_status'] == 3) ||
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 &&  in_array($order_info['return_check_status'], array(5,6,7)) && $car_info['car_source'] ==1 ) ||
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && $car_info['car_source'] ==2 )
            ) {
             $data['content'][] = array(
                "type"=>"group",
                "title"=>"优惠信息",
                "items"=>$items
            );
        }
        //车商自行过户 没有交付服务费   
        if ($order_info['transfer_type'] == 1) {
            $order_info['transfer_fee'] = 0;
        }
        $order_info['success_price'] = $order_info['bidding_best_price'] > $order_info['bid_best_price'] ? $order_info['bidding_best_price'] : $order_info['bid_best_price'];
        //应付总款
        $should_pay = $order_info['success_price'] + $order_info['commision'] + $order_info['transfer_fee'] - $used_coupon - $raffle - $order_info['compensation'];
        $data['content'][0]['should_pay'] = "应付总款：".(int)$should_pay. " 元";

        //支付信息
        $items1 = array();
        $label = '';
        if($order_info['consult_increase'] > 0){
            $label = "(磋商)";
        }
        $items1[] = array('type'=>'name_value','name' => '拍卖最高价'.$label, 'value' => (int)$order_info['success_price'] . " 元");
        if ($order_info['commision'] > 0) {
           $items1[] = array('type'=>'name_value' ,'name' => '交易服务费', 'value' => "+ " . (int)$order_info['commision'] . " 元");
        }
        if ($order_info['transfer_fee'] > 0 && $order_info['transfer_type'] != 1) {
        // if ($order_info['transfer_fee'] > 0 && $order_info['transfer_type'] != 1) {
            $items1[] = array('type'=>'name_value' ,'name' => '交付服务费', 'value' => "+ " . (int)$order_info['transfer_fee'] . " 元");
        }
        if ($order_info['compensation'] > 0) {
            $items1[] = array('type'=>'name_value' ,'name' => '仲裁补偿', 'value' => "- " . (int)$order_info['compensation'] . " 元");
        }
        if ($used_coupon) {
            $items1[] = array('type'=>'name_value' ,'name' => '代金券', 'value' => "- " . (int)$used_coupon . " 元");
        }
        if ($raffle) {
            $items1[] = array('type'=>'name_value' ,'name' => '抽奖立减', 'value' => "- " . (int)$raffle . " 元");
        }
        $items1[] =array('type'=>'total_pay' ,'name' => '应付总款', 'value' =>  (int)$should_pay . " 元");
        if (!empty( $items1)) {
             $data['content'][] = array(
                "type"=>"group",
                "title"=>"支付信息",
                "items"=>$items1
                );
        }
        // $car_id = $order_info['car_id'];
        // if ($car_id) {
        //     $data['content'][]= array(
        //         "type"=>"report",
        //         "title"=>"检测报告",
        //         "car_id"=>$car_id
        //     );
        // }        
        $this->api_200($data);

    }

    /**
     * 车辆结算页  客户端v1.3.0版本用接口
     * @author luchao 16-08-18
     */
    public function car_statement_v130(){
        $order_id = I('post.order_id/d', 0);
        $dealer_id = I('post.dealer_id/d', $this->dealer_id);
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        $o = new AuOrder($order_id);
        $d = new MyAuctioned($this->dealer_id);
        $order_info = $o->detail();
        $auctioned = $d->get_by_order_id($order_id);
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();
        $cm = new CarModel();
        $a = new Address();
        $city_name = $a->get_name_by_code($car_info['location_area']);
        $series = $cm->get_model_by_id($car_info['series_id'], 'series');
        $car_model = '['.$city_name.'] '.$series['name'] . ' ' . $car_info['car_cc'] . ($car_info['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_info['gearbox']);
        $img = Car::get_pic_by_key($order_info['car_id'], "p_left_front45");//左前45°图片 
         //判断车商是否授信用户  0.无授信的车商  1.授信的车商
        $dealer = new Dealer($dealer_id);
        $dealer_credit_info = $dealer->get_dealer_credit();
        $data = array();
        $data['content'][] = array(
                "type"=>"header",
                "car_name"=>$car_model,
                "img"=>$img['pic_url'],
                "summary"=>$order_info['order_no']."/".C('TRANSFER_LIMIT.' . $car_info['transfer_limit'])."/".C('TAKE_METHOD.' . $auctioned['take_method']),
                "is_credit"=>0
            );
        $items = array();
        //代金券
        $Coupon = new CouponList();
        $coupon_money = $Coupon->getSumCouponCost($dealer_id, $order_id);
        if ($coupon_money) {
            $used_coupon = $coupon_money > $order_info['coupon'] ? $order_info['coupon'] : $coupon_money;
            $items[] = array("type"=>"name_value","name"=>"代金券","value"=>"-".(int)$used_coupon. " 元");
        }elseif (!$coupon_money && $order_info['coupon']>0 ) {
            // $items[] = array("type"=>"coupon","name"=>"代金券","value"=>"可用".$order_info['coupon']. " 元","order_coupon"=>(int)$order_info['coupon']);
            $items[] = array("type"=>"coupon","name"=>"代金券","value"=>"未使用","order_coupon"=>(int)$order_info['coupon']);
        }
        //抽奖
        $lottery = new Raffle();
        $arr = $lottery->find_card_activity($order_id,1);//取出已抽奖的信息
        if ($arr['state']>0) {
            $raffle = $arr['price'];
            $items[] = array("type"=>"name_value","name"=>"抽奖立减","value"=>"-".(int)$raffle. " 元");
        }elseif ($arr && $arr['state']==0 ){
            $items[] = array("type"=>"activity","name"=>"抽奖立减","value"=>"未抽奖","url"=>APP_URL.'Raffle/raffle/type/1/order_id/'.$order_id,"title"=>"抽奖");
        }
        if (
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && $order_info['check_car_status'] == 3) ||
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && in_array($order_info['return_check_status'], array(5,6,7))&& $car_info['car_source'] ==1 ) ||
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && $car_info['car_source'] ==2 )
            ) {
             $data['content'][] = array(
                "type"=>"group",
                "title"=>"优惠信息",
                "items"=>$items
            );
        }
        //车商自行过户 没有交付服务费
        if ($order_info['transfer_type'] == 1) {
            $order_info['transfer_fee'] = 0;
        }
        $order_info['success_price'] = $order_info['bidding_best_price'] > $order_info['bid_best_price'] ? $order_info['bidding_best_price'] : $order_info['bid_best_price'];
        //应付总款
         $should_pay = $order_info['success_price'] + $order_info['commision'] + $order_info['transfer_fee'] - $used_coupon - $raffle - $order_info['compensation'];
        $data['content'][0]['should_pay'] = "应付总款：".(int)$should_pay. " 元";

        //支付信息
        $label = '';
        if($order_info['consult_increase'] > 0){
            $label = "(磋商)";
        }
        $items1[] = array('type'=>'name_value','name' => '拍卖最高价'.$label, 'value' => (int)$order_info['success_price'] . " 元");
        if ($order_info['commision'] > 0) {
           $items1[] = array('type'=>'name_value' ,'name' => '交易服务费', 'value' => "+ " . (int)$order_info['commision'] . " 元");
        }
        if ($order_info['transfer_fee'] > 0 && $order_info['transfer_type'] != 1) {
        // if ($order_info['transfer_fee'] > 0 && $order_info['transfer_type'] != 1) {
            $items1[] = array('type'=>'name_value' ,'name' => '交付服务费', 'value' => "+ " . (int)$order_info['transfer_fee'] . " 元");
        }
        if ($order_info['compensation'] > 0) {
            $items1[] = array('type'=>'name_value' ,'name' => '仲裁补偿', 'value' => "- " . (int)$order_info['compensation'] . " 元");
        }
        if ($used_coupon) {
            $items1[] = array('type'=>'name_value' ,'name' => '代金券', 'value' => "- " . (int)$used_coupon . " 元");
        }
        if ($raffle) {
            $items1[] = array('type'=>'name_value' ,'name' => '抽奖立减', 'value' => "- " . (int)$raffle . " 元");
        }
        $items1[] =array('type'=>'total_pay' ,'name' => '应付总款', 'value' =>  (int)$should_pay . " 元");
        if (!empty( $items1)) {
             $data['content'][] = array(
                "type"=>"group",
                "title"=>"支付信息",
                "items"=>$items1
                );
        }
        $this->api_200($data);

    }

       /**
     * 车辆结算页  客户端v1.3.0版本用接口
     * @author luchao 16-08-18
     */
    public function car_statement_v140(){
        $order_id = I('post.order_id/d', 0);
        $dealer_id = I('post.dealer_id/d', $this->dealer_id);
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        $o = new AuOrder($order_id);
        $d = new MyAuctioned($this->dealer_id);
        $order_info = $o->detail();
        $auctioned = $d->get_by_order_id($order_id);
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();
        $cm = new CarModel();
        $a = new Address();
        $city_name = $a->get_name_by_code($car_info['location_area']);
        $series = $cm->get_model_by_id($car_info['series_id'], 'series');
        $car_model = '['.$city_name.'] '.$series['name'] . ' ' . $car_info['car_cc'] . ($car_info['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_info['gearbox']);
        $img = Car::get_pic_by_key($order_info['car_id'], "p_left_front45");//左前45°图片 
         //判断车商是否授信用户  0.无授信的车商  1.授信的车商
        $dealer = new Dealer($dealer_id);
        $dealer_credit_info = $dealer->get_dealer_credit();
        $data = array();
        $data['content'][] = array(
                "type"=>"header",
                "car_name"=>$car_model,
                "img"=>$img['pic_url'],
                "summary"=>$order_info['order_no']."/".C('TRANSFER_LIMIT.' . $car_info['transfer_limit'])."/".C('TAKE_METHOD.' . $auctioned['take_method']),
                "is_credit"=>($dealer_credit_info['is_credit']?$dealer_credit_info['is_credit']:0)
            );
        $items = array();
        //代金券
        $Coupon = new CouponList();
        $coupon_money = $Coupon->getSumCouponCost($dealer_id, $order_id);
        if ($coupon_money) {
            $used_coupon = $coupon_money > $order_info['coupon'] ? $order_info['coupon'] : $coupon_money;
            $items[] = array("type"=>"name_value","name"=>"代金券","value"=>"-".(int)$used_coupon. " 元");
        }elseif (!$coupon_money && $order_info['coupon']>0 ) {
            // $items[] = array("type"=>"coupon","name"=>"代金券","value"=>"可用".$order_info['coupon']. " 元","order_coupon"=>(int)$order_info['coupon']);
            $items[] = array("type"=>"coupon","name"=>"代金券","value"=>"未使用","order_coupon"=>(int)$order_info['coupon']);
        }
        //抽奖
        $lottery = new Raffle();
        $arr = $lottery->find_card_activity($order_id,1);//取出已抽奖的信息
        if ($arr['state']>0) {
            $raffle = $arr['price'];
            $items[] = array("type"=>"name_value","name"=>"抽奖立减","value"=>"-".(int)$raffle. " 元");
        }elseif ($arr && $arr['state']==0 ){
            $items[] = array("type"=>"activity","name"=>"抽奖立减","value"=>"未抽奖","url"=>APP_URL.'Raffle/raffle/type/1/order_id/'.$order_id,"title"=>"抽奖");
        }
        if (
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && $order_info['check_car_status'] == 3) ||
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && in_array($order_info['return_check_status'], array(5,6,7)) && $car_info['car_source'] ==1 ) ||
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && $car_info['car_source'] ==2 )
            ) {
             $data['content'][] = array(
                "type"=>"group",
                "title"=>"优惠信息",
                "items"=>$items
            );
        }
        //车商自行过户 没有交付服务费
        if ($order_info['transfer_type'] == 1) {
            $order_info['transfer_fee'] = 0;
        }
        $order_info['success_price'] = $order_info['bidding_best_price'] > $order_info['bid_best_price'] ? $order_info['bidding_best_price'] : $order_info['bid_best_price'];
        //应付总款
         $should_pay = $order_info['success_price'] + $order_info['commision'] + $order_info['transfer_fee'] - $used_coupon - $raffle - $order_info['compensation'];
        $data['content'][0]['should_pay'] = "应付总款：".(int)$should_pay. " 元";

        //支付信息
        $label = '';
        if($order_info['consult_increase'] > 0){
            $label = "(磋商)";
        }
        $items1[] = array('type'=>'name_value','name' => '拍卖最高价'.$label, 'value' => (int)$order_info['success_price'] . " 元");
        if ($order_info['commision'] > 0) {
           $items1[] = array('type'=>'name_value' ,'name' => '交易服务费', 'value' => "+ " . (int)$order_info['commision'] . " 元");
        }
        if ($order_info['transfer_fee'] > 0 && $order_info['transfer_type'] != 1) {
            $items1[] = array('type'=>'name_value' ,'name' => '交付服务费', 'value' => "+ " . (int)$order_info['transfer_fee'] . " 元");
        }
        if ($order_info['compensation'] > 0) {  
            $items1[] = array('type'=>'name_value' ,'name' => '仲裁补偿', 'value' => "- " . (int)$order_info['compensation'] . " 元");
        }
        if ($used_coupon) {
            $items1[] = array('type'=>'name_value' ,'name' => '代金券', 'value' => "- " . (int)$used_coupon . " 元");
        }
        if ($raffle) {
            $items1[] = array('type'=>'name_value' ,'name' => '抽奖立减', 'value' => "- " . (int)$raffle . " 元");
        }
        $items1[] =array('type'=>'total_pay' ,'name' => '应付总款', 'value' =>  (int)$should_pay . " 元");
        if (!empty( $items1)) {
             $data['content'][] = array(
                "type"=>"group",
                "title"=>"支付信息",
                "items"=>$items1
                );
        }
        $this->api_200($data);
    }
    public function car_statement_v151(){
        $order_id = I('post.order_id/d', 0);
        $dealer_id = I('post.dealer_id/d', $this->dealer_id);
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        $o = new AuOrder($order_id);
        $d = new MyAuctioned($this->dealer_id);
        $order_info = $o->detail();
        $auctioned = $d->get_by_order_id($order_id);
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();
        $cm = new CarModel();
        $a = new Address();
        $city_name = $a->get_name_by_code($car_info['location_area']);
        $series = $cm->get_model_by_id($car_info['series_id'], 'series');
        $car_model = '['.$city_name.'] '.$series['name'] . ' ' . $car_info['car_cc'] . ($car_info['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_info['gearbox']);
        $img = Car::get_pic_by_key($order_info['car_id'], "p_left_front45");//左前45°图片
        //判断车商是否授信用户  0.无授信的车商  1.授信的车商
        $dealer = new Dealer($dealer_id);
        $dealer_credit_info = $dealer->get_dealer_credit();
        $data = array();
        $data['content'][] = array(
            "type"=>"header",
            "car_name"=>$car_model,
            "img"=>$img['pic_url'],
            "summary"=>$order_info['order_no']."/".C('TRANSFER_LIMIT.' . $car_info['transfer_limit'])."/".C('TAKE_METHOD.' . $auctioned['take_method']),
            "is_credit"=>($dealer_credit_info['is_credit']?$dealer_credit_info['is_credit']:0)
        );
        $items = array();
        $Coupon = new CouponList();
        if($order_info['coupon']>0){  //判断是否可以使用代金券
            //代金券
            //用户选择的代金券
            $redis = new PhpRedis();
            $arr = ['order_id'=>$order_id];
            $redis_key = getRedisKeyByCode('REDIS_KEY','100000',$arr);
            $confirm_key = getRedisKeyByCode('REDIS_KEY','100001',$arr);
            $redis_res = $redis->exists($confirm_key);
            if($redis_res){
                $redis_coupon_ids = $redis->get($redis_key);
                $res = array();
                $coupon_ids = explode(',',$redis_coupon_ids); //判断是否代金券已经结算
                foreach($coupon_ids as $k){
                    $coupon = M('dealer_coupon')->where("dealer_id='" . $this->dealer_id . "' AND coupon_id='" . $k . "'")->find();
                    if($coupon['use_status'] != 0){
                        $re = 'false';
                        $res[] = $re;
                    }
                }
                if($redis_coupon_ids && !in_array('false',$res)){
                    $coupon_money = $Coupon->get_confirm_coupon($redis_coupon_ids);
                }else if($redis_coupon_ids == 0){
                    $coupon_money = 0;
                }
            }else{
                $coupon_list = $Coupon->get_coupon_list($this->dealer_id);
                $new_coupon_list = $Coupon->pase_coupon($coupon_list);
                $default_coupon_id = $Coupon->get_coupon_id($new_coupon_list,$order_info['coupon']); //默认可以使用的代金券id
                $default_coupon_ids = implode(',',$default_coupon_id);
                $coupon_money = $Coupon->get_confirm_coupon($default_coupon_ids);  //默认使用代金券的金额
                $redis->set($redis_key,$default_coupon_ids);
            }
        }
        if ($coupon_money) {
            $used_coupon = $coupon_money > $order_info['coupon'] ? $order_info['coupon'] : $coupon_money;
            $items[] = array(
                "type"=>"coupon",
                "name"=>"代金券",
                "value"=>"-".(int)$used_coupon. " 元",
                "used_coupon"=>$used_coupon,
                "is_system_pre"=> $redis_res ? false : true,
                "order_coupon"=>(int)$order_info['coupon']
            );
        }elseif (!$coupon_money && $order_info['coupon']>0 ) {
            // $items[] = array("type"=>"coupon","name"=>"代金券","value"=>"可用".$order_info['coupon']. " 元","order_coupon"=>(int)$order_info['coupon']);
            $items[] = array("type"=>"coupon","name"=>"代金券","value"=>"未使用","order_coupon"=>(int)$order_info['coupon']);
        }
        //抽奖
        $lottery = new Raffle();
        $arr = $lottery->find_card_activity($order_id,1);//取出已抽奖的信息
        if ($arr['state']>0) {
            $raffle = $arr['price'];
            $items[] = array("type"=>"name_value","name"=>"抽奖立减","value"=>"-".(int)$raffle. " 元");
        }elseif ($arr && $arr['state']==0 ){
            $items[] = array("type"=>"activity","name"=>"抽奖立减","value"=>"未抽奖","url"=>APP_URL.'Raffle/raffle/type/1/order_id/'.$order_id,"title"=>"抽奖");
        }
        if (
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && $order_info['check_car_status'] == 3) ||
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && in_array($order_info['return_check_status'], array(5,6,7)) && $car_info['car_source'] ==1 ) ||
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && $car_info['car_source'] ==2 )
        ) {
            $data['content'][] = array(
                "type"=>"group",
                "title"=>"优惠信息",
                "items"=>$items
            );
        }
        //车商自行过户 没有交付服务费
        if ($order_info['transfer_type'] == 1) {
            $order_info['transfer_fee'] = 0;
        }
        $order_info['success_price'] = $order_info['bidding_best_price'] > $order_info['bid_best_price'] ? $order_info['bidding_best_price'] : $order_info['bid_best_price'];
        $bl = new BuyCarList($this->dealer_id);
        //场次活动
        $res_activity = $bl->is_scene_activity($order_info['scene_id']);
        if(!empty($res_activity)){
            //根据场次活动减免规则id找到减免规则
            foreach($res_activity as $k => $v){
                if($v['rules_type'] == 2){ //如果减免规则的rules_type == 2 说明是阶梯立减 去activity_rules表中找到相应的详细规则
                    $scene_activity_amount = $bl->get_activity_rules_price($v['scene_activity_id'],$order_info['success_price']);
                }else if($v['rules_type'] == 1){ //如果减免规则rules_type == 1 说明是活动统一立减,取出scene_activity['amount'] 即可
                    $scene_activity_amount = $v['amount'];
                }
            }
        }else{
            $scene_activity_amount = 0; //判断如果没有活动减免价格 则设置scene_activity_amount的值为0;
        }
        //应付总款
        $should_pay = $order_info['success_price'] + $order_info['commision'] + $order_info['transfer_fee'] - $used_coupon - $raffle - $order_info['compensation'] - $scene_activity_amount;
        $data['content'][0]['should_pay'] = "应付总款：".(int)$should_pay. " 元";

        //支付信息
        $label = '';
        if($order_info['consult_increase'] > 0){
            $label = "(磋商)";
        }
        $items1[] = array('type'=>'name_value','name' => '拍卖最高价'.$label, 'value' => (int)$order_info['success_price'] . " 元");
        if ($order_info['commision'] > 0) {
            $items1[] = array('type'=>'name_value' ,'name' => '交易服务费', 'value' => "+ " . (int)$order_info['commision'] . " 元");
        }
        if ($order_info['transfer_fee'] > 0 && $order_info['transfer_type'] != 1) {
            $items1[] = array('type'=>'name_value' ,'name' => '交付服务费', 'value' => "+ " . (int)$order_info['transfer_fee'] . " 元");
        }
        if ($order_info['compensation'] > 0) {
            $items1[] = array('type'=>'name_value' ,'name' => '仲裁补偿', 'value' => "- " . (int)$order_info['compensation'] . " 元");
        }
        if ($used_coupon) {
            $items1[] = array('type'=>'name_value' ,'name' => '代金券', 'value' => "- " . (int)$used_coupon . " 元");
        }
        if ($raffle) {
            $items1[] = array('type'=>'name_value' ,'name' => '抽奖立减', 'value' => "- " . (int)$raffle . " 元");
        }
        if ($scene_activity_amount > 0) {
            $items1[] = array('type'=>'name_value' ,'name' => '活动减免', 'value' => "- " . (int)$scene_activity_amount . " 元");
        }
        $items1[] =array('type'=>'total_pay' ,'name' => '应付总款', 'value' =>  (int)$should_pay . " 元");
        if (!empty( $items1)) {
            $data['content'][] = array(
                "type"=>"group",
                "title"=>"支付信息",
                "items"=>$items1
            );
        }
        $this->api_200($data);

    }
    public function car_statement_v180(){
        $order_id = I('post.order_id/d', 0);
        $dealer_id = I('post.dealer_id/d', $this->dealer_id);
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        $o = new AuOrder($order_id);
        $d = new MyAuctioned($this->dealer_id);
        $order_info = $o->detail();
        $bl = new BuyCarList($this->dealer_id);
        $auctioned = $d->get_by_order_id($order_id);
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();
        $cm = new CarModel();
        $a = new Address();
        $city_name = $a->get_name_by_code($car_info['location_area']);
        $series = $cm->get_model_by_id($car_info['series_id'], 'series');
        $car_model = '['.$city_name.'] '.$series['name'] . ' ' . $car_info['car_cc'] . ($car_info['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_info['gearbox']);
        $img = Car::get_pic_by_key($order_info['car_id'], "p_left_front45");//左前45°图片
        //判断车商是否授信用户  0.无授信的车商  1.授信的车商
        $dealer = new Dealer($dealer_id);
        $dealer_credit_info = $dealer->get_dealer_credit();
        $data = array();
        $data['content'][] = array(
            "type"=>"header",
            "car_name"=>$car_model,
            "img"=>$img['pic_url'],
            "summary"=>$order_info['order_no']."/".C('TRANSFER_LIMIT.' . $car_info['transfer_limit'])."/".C('TAKE_METHOD.' . $auctioned['take_method']),
            "is_credit"=>($dealer_credit_info['is_credit']?$dealer_credit_info['is_credit']:0)
        );
        $order_info['success_price'] = $order_info['bidding_best_price'] > $order_info['bid_best_price'] ? $order_info['bidding_best_price'] : $order_info['bid_best_price'];
        $coupon_limit = SystemConf::getConfByName('COUPON_LIMIT');
        $items = array();
        $Coupon = new CouponList();
        if($order_info['coupon']>0 && $order_info['success_price'] >= $coupon_limit['value']){  //判断是否可以使用代金券
            //代金券
            //用户选择的代金券
            $redis = new PhpRedis();
            $arr = ['order_id'=>$order_id];
            $redis_key = getRedisKeyByCode('REDIS_KEY','100000',$arr);
            $confirm_key = getRedisKeyByCode('REDIS_KEY','100001',$arr);
            $redis_res = $redis->exists($confirm_key);
            if($redis_res){
                $redis_coupon_ids = $redis->get($redis_key);
                $res = array();
                $coupon_ids = explode(',',$redis_coupon_ids); //判断是否代金券已经结算
                foreach($coupon_ids as $k){
                    $coupon = M('dealer_coupon')->where("dealer_id='" . $this->dealer_id . "' AND coupon_id='" . $k . "'")->find();
                    if($coupon['use_status'] != 0){
                        $re = 'false';
                        $res[] = $re;
                    }
                }
                if($redis_coupon_ids && !in_array('false',$res)){
                    $coupon_money = $Coupon->get_confirm_coupon($redis_coupon_ids);
                }else if($redis_coupon_ids == 0){
                    $coupon_money = 0;
                }
            }else{
                $coupon_list = $Coupon->get_coupon_list($this->dealer_id);
                $new_coupon_list = $Coupon->pase_coupon($coupon_list);
                $default_coupon_id = $Coupon->get_coupon_id($new_coupon_list,$order_info['coupon']); //默认可以使用的代金券id
                $default_coupon_ids = implode(',',$default_coupon_id);
                $coupon_money = $Coupon->get_confirm_coupon($default_coupon_ids);  //默认使用代金券的金额
                $redis->set($redis_key,$default_coupon_ids);
            }
        }
        if ($coupon_money) {
            $used_coupon = $coupon_money > $order_info['coupon'] ? $order_info['coupon'] : $coupon_money;
            $items[] = array(
                "type"=>"coupon",
                "name"=>"代金券",
                "value"=>"-".(int)$used_coupon. " 元",
                "used_coupon"=>$used_coupon,
                "is_system_pre"=> $redis_res ? false : true,
                "order_coupon"=>(int)$order_info['coupon']
            );
        }elseif (!$coupon_money && $order_info['coupon']>0 && $order_info['success_price'] >= $coupon_limit['value']) {
            // $items[] = array("type"=>"coupon","name"=>"代金券","value"=>"可用".$order_info['coupon']. " 元","order_coupon"=>(int)$order_info['coupon']);
            $items[] = array("type"=>"coupon","name"=>"代金券","value"=>"未使用","order_coupon"=>(int)$order_info['coupon']);
        }
        //抽奖
        $lottery = new Raffle();
        $arr = $lottery->find_card_activity($order_id,1);//取出已抽奖的信息
        if ($arr['state']>0) {
            $raffle = $arr['price'];
            $items[] = array("type"=>"name_value","name"=>"抽奖立减","value"=>"-".(int)$raffle. " 元");
        }elseif ($arr && $arr['state']==0 ){
            $items[] = array("type"=>"activity","name"=>"抽奖立减","value"=>"未抽奖","url"=>APP_URL.'Raffle/raffle/type/1/order_id/'.$order_id,"title"=>"抽奖");
        }
        $dealer = new Dealer($this->dealer_id);
        $dealer_info = $dealer->detail();
        if($dealer_info['level'] == 2){
            $list['type'] = "transfer_type";
            $list['name'] = "过户类型";
            $list['button_info'][0]['name'] = "平台代办";
            $list['button_info'][0]['value'] = "0";
            if($order_info['transfer_type'] == 0){
                $list['button_info'][0]['selected'] = true;
            }
            $list['button_info'][1]['name'] = "用户自办";
            $list['button_info'][1]['value'] = "1";
            if($order_info['transfer_type'] == 1){
                $list['button_info'][1]['selected'] = true;
            }
            $items[] = $list;
        }
        if (
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && $order_info['check_car_status'] == 3) ||
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && in_array($order_info['return_check_status'], array(5,6,7)) && $car_info['car_source'] ==1 ) ||
            ($order_info['dealer_pay_status'] == 0 && $order_info['status'] == 8 && $car_info['car_source'] ==2 )
        ) {
            $data['content'][] = array(
                "type"=>"group",
                "title"=>"优惠信息",
                "items"=>$items
            );
        }
        //车商自行过户 没有交付服务费
        if ($order_info['transfer_type'] == 1) {
            $order_info['transfer_fee'] = 0;
        }
        //场次活动
        $res_activity = $bl->is_scene_activity($order_info['scene_id']);
        if(!empty($res_activity)){
            //根据场次活动减免规则id找到减免规则
            foreach($res_activity as $k => $v){
                if($v['rules_type'] == 2){ //如果减免规则的rules_type == 2 说明是阶梯立减 去activity_rules表中找到相应的详细规则
                    $scene_activity_amount = $bl->get_activity_rules_price($v['scene_activity_id'],$order_info['success_price']);
                }else if($v['rules_type'] == 1){ //如果减免规则rules_type == 1 说明是活动统一立减,取出scene_activity['amount'] 即可
                    $scene_activity_amount = $v['amount'];
                }
            }
        }else{
            $scene_activity_amount = 0; //判断如果没有活动减免价格 则设置scene_activity_amount的值为0;
        }
        //应付总款
        $should_pay = $order_info['success_price'] + $order_info['commision'] + $order_info['transfer_fee'] - $used_coupon - $raffle - $order_info['compensation'] - $scene_activity_amount;
        $data['content'][0]['should_pay'] = "应付总款：".(int)$should_pay. " 元";

        //支付信息
        $label = '';
        if($order_info['consult_increase'] > 0){
            $label = "(磋商)";
        }
        $items1[] = array('type'=>'name_value','name' => '拍卖最高价'.$label, 'value' => (int)$order_info['success_price'] . " 元");
        if ($order_info['commision'] > 0) {
            $items1[] = array('type'=>'name_value' ,'name' => '交易服务费', 'value' => "+ " . (int)$order_info['commision'] . " 元");
        }
        if ($order_info['transfer_fee'] > 0 && $order_info['transfer_type'] != 1) {
            $items1[] = array('type'=>'name_value' ,'name' => '交付服务费', 'value' => "+ " . (int)$order_info['transfer_fee'] . " 元");
        }
        if ($order_info['compensation'] > 0) {
            $items1[] = array('type'=>'name_value' ,'name' => '仲裁补偿', 'value' => "- " . (int)$order_info['compensation'] . " 元");
        }
        if ($used_coupon) {
            $items1[] = array('type'=>'name_value' ,'name' => '代金券', 'value' => "- " . (int)$used_coupon . " 元");
        }
        if ($raffle) {
            $items1[] = array('type'=>'name_value' ,'name' => '抽奖立减', 'value' => "- " . (int)$raffle . " 元");
        }
        if ($scene_activity_amount > 0) {
            $items1[] = array('type'=>'name_value' ,'name' => '活动减免', 'value' => "- " . (int)$scene_activity_amount . " 元");
        }
        $items1[] =array('type'=>'total_pay' ,'name' => '应付总款', 'value' =>  (int)$should_pay . " 元");
        if (!empty( $items1)) {
            $data['content'][] = array(
                "type"=>"group",
                "title"=>"支付信息",
                "items"=>$items1
            );
        }
        $this->api_200($data);

    }

    /**
    * 支付方式 客户端v1.3.0版本用接口
    * @author luhao 16-08-19
    */
    public function pay_mode(){
        $order_id = I('post.order_id', 0);
        $dealer_id = I('post.dealer_id', $this->dealer_id);
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        $o = new AuOrder($order_id);
        $d = new MyAuctioned($this->dealer_id);
        $order_info = $o->detail();
        $auctioned = $d->get_by_order_id($order_id);
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();
        $cm = new CarModel();
        $a = new Address();
        $city_name = $a->get_name_by_code($car_info['location_area']);
        $series = $cm->get_model_by_id($car_info['series_id'], 'series');
        $car_model = '['.$city_name.'] '.$series['name'] . ' ' . $car_info['car_cc'] . ($car_info['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_info['gearbox']);
        $img = Car::get_pic_by_key($order_info['car_id'], "p_left_front45");//左前45°图片 
        $data = array();
        $data['content'][] = array(
                "type"=>"header",
                "car_name"=>$car_model,
                "img"=>$img['pic_url'],
                "summary"=>$order_info['order_no']."/".C('TRANSFER_LIMIT.' . $car_info['transfer_limit'])."/".C('TAKE_METHOD.' . $auctioned['take_method'])
            );
        $items = array();
        //代金券
        $Coupon = new CouponList();
        $coupon_money = $Coupon->getSumCouponCost($dealer_id, $order_id);
        if ($coupon_money) {
            $used_coupon = $coupon_money > $order_info['coupon'] ? $order_info['coupon'] : $coupon_money;
        }
        //抽奖
        $lottery = new Raffle();
        $arr = $lottery->find_card_activity($order_id,1);//取出已抽奖的信息
        if ($arr['state']>0) {
            $raffle = $arr['price'];
        }
        //车商自行过户 没有交付服务费
        if ($order_info['transfer_type'] == 1) {
            $order_info['transfer_fee'] = 0;
        }
        
        $success_price = $order_info['bidding_best_price'] > $order_info['bid_best_price'] ? $order_info['bidding_best_price'] : $order_info['bid_best_price'];
        //应付总款
        $should_pay = $success_price + $order_info['commision'] + $order_info['transfer_fee'] - $used_coupon - $raffle - $order_info['compensation'];
        $data['content'][0]['should_pay'] = "应付总款：".(int)$should_pay. " 元";
        $data['content'][0]['should_pay_number'] = $should_pay;
        $dealer = new Dealer($dealer_id);
        //获取车商授信信息
        $dealer_credit_info = $dealer->get_dealer_credit();
        if ($dealer_credit_info['is_credit'] == 1) {
            $map = array();
            $map['product_id'] = C('PROD_CAR_OLD_CLCW.0');
            $map['out_user_code'] = $dealer_id;
            $ximu = new XimuApi();
            $res = $ximu->_get('CREDIT','queryallowbal',$map);
            $items[] = array('type'=>'pcloan_pay','name'=>'拍车贷','value'=>'可用额度'.($res['data']['available_bal']/100)."元");
        }
        $items[] = array('type'=>'cash_pay','name'=>'全款');
        $data['content'][] = array(
            "type"=>"group",
            "items"=>$items
        );
        $this->api_200($data);
    }

    /**
    * 贷款支付 客户端v1.3.0版本用接口
    * @author luhao 16-08-19
    */
    public function loan_pay(){
        $order_id = I('post.order_id/d', 0);
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }
        $o = new AuOrder($order_id);
        $order_info = $o->detail();
        $d = new MyAuctioned($this->dealer_id);
        $auctioned = $d->get_by_order_id($order_id);
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();
        $cm = new CarModel();
        $a = new Address();
        $city_name = $a->get_name_by_code($car_info['location_area']);
        $series = $cm->get_model_by_id($car_info['series_id'], 'series');
        $car_model = '['.$city_name.'] '.$series['name'] . ' ' . $car_info['car_cc'] . ($car_info['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_info['gearbox']);
        $img = Car::get_pic_by_key($order_info['car_id'], "p_left_front45");//左前45°图片 
        $data = array();
        $data['content'][] = array(
                "type"=>"header",
                "car_name"=>$car_model,
                "img"=>$img['pic_url'],
                "summary"=>$order_info['order_no']."/".C('TRANSFER_LIMIT.' . $car_info['transfer_limit'])."/".C('TAKE_METHOD.' . $auctioned['take_method'])
            );
        $items = array();
        //代金券
        $Coupon = new CouponList();
        $coupon_money = $Coupon->getSumCouponCost($this->dealer_id, $order_id);
        if ($coupon_money) {
            $used_coupon = $coupon_money > $order_info['coupon'] ? $order_info['coupon'] : $coupon_money;
        }
        //抽奖
        $lottery = new Raffle();
        $arr = $lottery->find_card_activity($order_id,1);//取出已抽奖的信息
        if ($arr['state']>0) {
            $raffle = $arr['price'];
        }
        //车商自行过户 没有交付服务费
        if ($order_info['transfer_type'] == 1) {
            $order_info['transfer_fee'] = 0;
        }
        $success_price = $order_info['bidding_best_price'] > $order_info['bid_best_price'] ? $order_info['bidding_best_price'] : $order_info['bid_best_price'];
        //应付总款
        $should_pay = $success_price + $order_info['commision'] + $order_info['transfer_fee'] - $used_coupon - $raffle - $order_info['compensation'];
        $data['content'][0]['should_pay'] = "应付总款：".(int)$should_pay. " 元";
        $data['content'][0]['should_pay_number'] = (int)$should_pay;

        $res = $this->get_transaction_limit($order_id,$should_pay);
        //可用额度 available_bal 
        $all_available_bal = $res['data']['available_bal']/100;
        //可贷额度成数 bal_rate
        $bal_rate = $res['data']['bal_rate'];
        //收费年利率 charge_rate
        $charge_rate = $res['data']['charge_rate'];
        //应付总款大于30000元 必须要付首付 小于30000可以不付首付
        // if ($should_pay >30000) {
        // }else{
        // }
        //贷款金额 可待金额
        $available_bal = $should_pay*$bal_rate > $all_available_bal ? $all_available_bal : $should_pay*$bal_rate;
        //首付金额
        $first_pay = $should_pay - $available_bal;
        $loan_day = C('LOAN_DAY');
        //当前选中天数
        $day = C('CHECKED_DATE.0');
        $items = array();
        foreach ($loan_day as $key => $value) {
            if ($day == $value) {
                $items[] = array("name"=>$value."天","num"=>$value,"value"=>$value,"checked"=>true);
            }else{
                $items[] = array("name"=>$value."天","num"=>$value,"value"=>$value);
            }
        }
        $data['content'][] = array(
            "type"=>"loan_info",
            "first_pay"=>array("title"=>"首付金额","count"=>$first_pay,"hint"=>"应付总款大于3万，首付至少20%"),
            "loan_pay"=>array("title"=>"贷款金额","count"=>$available_bal,"hint"=>"可贷金额：".$available_bal),
            "loan_term"=>array("title"=>"贷款期限","items"=>$items),
            "loan_count"=>array("title"=>"贷款费用","rate"=>$charge_rate/360,"rate_info"=>"日利率".$charge_rate/(3.6)."%","pre_count"=>round($available_bal*$day*$charge_rate/360 ,4)),
            "loan_contract_url"=>APP_URL."/Trade/pact?dealer_id=".$this->dealer_id
        );
        $this->api_200($data);
    }

    /**
    * 申请支付 客户端v1.3.0版本用接口
    * @author luhao 16-09-13
    */
    public function apply_loan(){
        $order_id = I('post.order_id');
        $time = date('Y-m-d H:i:s');
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }
        $loan_money = I('post.loan_money')*100;
        if ($loan_money <= 0) {
            AuctionException::make_throw('1700002');
        }
        $loan_period = I('post.loan_period');
        $should_pay = I('post.should_pay')*100;
        $dealer_id = $this->dealer_id;
        $o = new AuOrder($order_id);
        $order_info = $o->detail();
        if ($order_info['status'] > 8 || $order_info['dealer_pay_status'] > 0 ) {
            AuctionException::make_throw('1700006');
        }
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();
        $first_pay_money = ($should_pay-$loan_money)/100;//
        // $is_free_all = false;
        //添加收款单
        $info = array();
        $info['collection_no'] = $first_pay_money > 0 ? genBillsNo("SK", 03) : genBillsNo("SK", 01); //获取付款单编号
        $info['status'] = 0; //状态都是未收
        $info['payment_type'] = $first_pay_money > 0 ?  3 : 2;
        //拍单基本信息
        $o = new AuOrder($order_id);
        $order_info = $o->detail();
        $bl = new BuyCarList($this->dealer_id);
        $final_amount = $bl->set_final_price($order_info['car_id'],$order_id,2);
        $first_pay_money > 0 ? $info['amount'] = $first_pay_money : $final_amount;
        $info['create_time'] = $time;
        M()->startTrans();
        if ($first_pay_money == 0) {
            $data = array();
            $data['dealer_pay_status'] = 3;
            $data['is_self_confirm'] = 1;
            $data['dealer_pay_mode'] = 2;
            $log_data = array(
            'pay_type' => '1',
            'amount'   => $should_pay/100,
            'pay_time' => $time,
            'is_loan'=>1,
            'pay_mode'=>3
            );
            $car_check_ret = $o->add_car_dealer_check();
            if (!$car_check_ret) {
                M()->rollback();
                echo Util::auto_jsonp_or_json($_REQUEST,array('code'=>500,'msg'=>'确认失败或数据已更新'));
                exit();
            }
            $result = $o->update($data);
            //记录收款信息
            $collection = new Collection();
            $log_result = $collection->update_by_order_id($order_id, $log_data);
            if (!$result || !$log_result) {
                M()->rollback();
                echo Util::auto_jsonp_or_json($_REQUEST,array('code'=>500,'msg'=>'确认失败或数据已更新'));
                exit;
            }
        }elseif ($first_pay_money > 0) {
            $data = array();
            $data['dealer_pay_status'] = 1;
            $data['dealer_pay_mode'] = 2;
            $data['is_self_confirm'] = 1;
            //首付款贷款
            $collection = new Collection();
            $proceedinfo = $collection->getProceedInfoByOrderID($order_id);
            $proceed_data = array();
            if ($proceedinfo) {
                $proceed_data = array(
                    'is_loan'=>1,
                    'pay_mode'=>2
                );
                $pay_res = $collection->update_by_order_id($order_id,$proceed_data);
            }else{
                $proceed_data = array(
                    'order_id'=>$order_id,
                    'is_loan'=>1,
                    'pay_mode'=>2
                );
                $pay_res = $collection->add($proceed_data);
            }
            $first_result = $o->update($data);
            //添加收款单信息
            $res = $o->set_collection($info);
            $oc = array();
            $oc['order_id'] = $order_id;
            $oc['payment_type'] = $first_pay_money > 0 ?  3 : 2;
            $oc['collection_id'] = $res;
            $oc['createtime'] = $time;
            $res2 = $bl->set_order_collections($oc);
            if (!$pay_res || !$first_result || !$res || !$res2) {
                M()->rollback();
                echo Util::auto_jsonp_or_json($_REQUEST,array('code'=>500,'msg'=>'确认失败或数据已更新'));
            }
            
        }

        $cm = new CarModel();
        $data = array();
        $data['out_list_code'] = $order_info['order_no'];//行业订单编号
        $data['product_id'] = C('PROD_CAR_OLD_CLCW.0');//产品id
        $data['out_user_id'] = $dealer_id;//登陆userid
        $data['out_user_code'] = $dealer_id;//用户唯一编号
        //交易信息
        $data['auc_car_id'] = $car_info['car_no'];//竞拍车辆编号
        $data['deal_state'] = C('ORDER_STATUS')[$order_info['status']];//交易状态
        $data['deal_end_date'] = $order_info['bidding_end_time'];//交易完成日期
        $data['car_deal_price'] = (string)$should_pay; //成交价格
        //车辆信息
        $data['car_id'] = $car_info['car_no'];//车辆编号
        $brand_name = $cm->get_model_by_id($car_info['brand_id'], 'brand');
        $series_name = $cm->get_model_by_id($car_info['series_id'], 'series');
        $model_name = $cm->get_model_by_id($car_info['model_id'], 'model');
        //车辆手续信息
        $car_procedure = $cm->get_procedure_by_car_id($order_info['car_id']);

        $data['car_mark_sign'] = $brand_name['name']?$brand_name['name']:'无';//品牌
        $data['car_serial'] = $series_name['name']?$series_name['name']:'无';//车系
        $data['car_model'] =  $model_name['name']?$model_name['name']:'无';//车款
        $data['car_out_year'] = $car_info['ex_factory_date']; //出厂年月
        $data['car_no'] = $car_info['plate_prefix']; //车牌号
        $data['car_chejia'] = $car_info['vin'];//车架
        $data['car_engi_no'] = $car_info['engine_no'];//发动机号
        $data['car_run_mile'] = $car_info['pointer_mileage'];//里程
        $data['car_no_date'] = $car_info['first_reg_date']." 00:00:00";//上牌日期
        $data['ns_date_to'] = $car_procedure['verify_expiry']." 00:00:00";//年审检验到期日
        $data['car_end_insurance'] = $car_procedure['com_insure_expiry']." 00:00:00";//交强险截止日期
        $data['scorerating'] = $car_info['composite_state'].$car_info['accident_level'];//评分等级
        $data['car_ep'] = C('EMISSION')[$car_info['emission']]; //环保标准
        $data['car_useage'] = C('USE_PROPERTIES')[$car_info['use_properties']];//用途
        $data['car_pailiang'] = $car_info['car_cc'];//排量
        $a = new Address();
        $city_name = $a->get_name_by_code($car_info['location_area']);
        $data['car_location'] = $city_name;//车辆所在地
        $car_guishu = $a->get_name_by_code($car_info['reg_city']);
        $data['car_guishu'] = $car_guishu;//归属地
        $data['car_isloan'] = 'NO';//有无购车贷款未还 yes or no
        //贷款的基本信息
        $data['apply_bal'] = $loan_money;//申贷金额
        $data['apply_time'] = $time;//申贷日期
        $data['loan_period'] = $loan_period; //贷款期限
        $data['loan_type'] = "DAY";//贷款期限每期的周期标识
        $data['charge_rate'] = "0.1800";//收费利率
        $inte_comp_kind = C('INTE_COMP_KIND.3');
        $data['inte_comp_kind'] = $inte_comp_kind;//利息的方式
        //用户的行为信息
        $data['platform_source'] = C('PLATFORM_CAR_OLD_CLCW.0') ;//来源
        $data['client_cookie'] = "无";//授权终端cookie
        $data['client_mac'] = "无";//客户mac
        $data['client_ip'] = get_client_ip();//客户ip
        $data['client_browser'] = $_SERVER['HTTP_USER_AGENT'];//客户浏览器
        $data['client_type'] = "PC";//设备类型
        $data['action_type'] = "SUBMIT_ORDER";//操作类型
        $data['action_date'] = $time;
        $ximu = new XimuApi();
        $res = $ximu->_get('ORDER','submitlist',$data);
        // var_dump($res);
        // die();
        if ($res['code'] == 200) {
            //贷款记录
            M()->commit();
            // if ($is_free_all) {
            //      \AuctionCore\CarDealer\AssetCenter::free_all($order_id);
            // }
            $map = array();
            $map['xm_list_code'] = $res['data']['xm_list_code'];
            $map['order_id'] = $order_id;
            $map['loan_money'] = $loan_money/100;
            $map['loan_day'] = $loan_period;
            $map['loan_status'] = 1;
            $map['first_pay_money'] = $first_pay_money;
            $map['createtime'] = $time;
            $res1 = $o->insert_loan_log($map);
            //全额贷款  
            if (!$res1) {
                echo Util::auto_jsonp_or_json($_REQUEST,array('code'=>500,'msg'=>'贷款日志更新失败'));
                exit;
            }
            //记录操作日志
            $log = array(
                'emp_id' => 0,
                'order_id' => $order_id,
                'car_id' => $order_info['car_id'],
                'owner_id' => 0,
                'action' => '确认收款' . $log_result
            );
            SystemLog::add($log);

            /**
             * 修改奖券状态 user_state ->1
             */
            $Raffle = new Raffle();
            $Raffle->card_change_state($order_id,1);

            $redis = new PhpRedis();
            $arr = ['order_id'=>$order_id];
            $redis_key = getRedisKeyByCode('REDIS_KEY','100019',$arr);
            $redis->del($redis_key);

            $this->build_pdf($dealer_id,$loan_money/100,$loan_period,$order_id);

            $this->api_200($res1);
        }
    }

    /**
    * 授信车商线下支付 客户端v1.3.0版本用接口
    * @author luhao 16-09-08
    */
    public function offline_payment(){
        $order_id = I('post.order_id',0);
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }
        $order = new AuOrder($order_id);
        $order_info = $order->detail();
        if ($order_info['dealer_pay_status'] > 0 || $order_info['is_self_confirm'] == 1) {
            AuctionException::make_throw('700045');
        }
        //车商是否授权
        $dealer = new Dealer($this->dealer_id);
        $dealer_credit_info = $dealer->get_dealer_credit();
        if (!$dealer_credit_info['is_credit']) {
            AuctionException::make_throw('1700004');
        }
        //授信车商是否结算
        $redis = new PhpRedis();
        $arr = ['order_id'=>$order_id];
        $redis_key = getRedisKeyByCode('REDIS_KEY','100019',$arr);
        $step = $redis->get($redis_key);
        if (!$step) {
            AuctionException::make_throw('1700005');
        }
        M()->startTrans();
        $data = array();
        $data['is_self_confirm'] = 1;
        $data['dealer_pay_status'] = 1;
        $res = $order ->updateOrder($data);
        $map = array();
        $payer_info = array();
        $payer_info['settlement_time'] = date('Y-m-d H:i:s');
        $map['order_id'] = array('eq',$order_id);
        $res1 = M('proceeds_log')->where($map)->save($payer_info);
        if ($res && $res1) {
            M()->commit();
            $this->api_200($res);
        } else {
            M()->rollback();
            AuctionException::make_throw('100066');
        }
    }

    /**
    * 完成结算 客户端v1.3.0版本用接口
    * @author luhao 16-08-19
    */
    public function complete_balance(){
        $order_id = I('post.order_id',0);
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }

        $order = new AuOrder($order_id);
        $order_info = $order->detail();
        if ($order_info['dealer_pay_status'] > 0 || $order_info['is_self_confirm'] == 1) {
            AuctionException::make_throw('700045');
        }
        //车商是否授权
        $dealer = new Dealer($this->dealer_id);
        $dealer_credit_info = $dealer->get_dealer_credit();
        if ($dealer_credit_info['is_credit'] == 1) {
            $redis = new PhpRedis();
            $arr = ['order_id'=>$order_id];
            $redis_key = getRedisKeyByCode('REDIS_KEY','100019',$arr);
            $res = $redis->set($redis_key,1);
            $map = array();
            $payer_info = array();
            $payer_info['settlement_time'] = date('Y-m-d H:i:s');
            $map['order_id'] = array('eq',$order_id);
            $res1 = M('proceeds_log')->where($map)->save($payer_info);
            if ($res && $res1) {
                $this->api_200($res);
            }else {
                AuctionException::make_throw('100066');
            }
        }else{
            M()->startTrans();
            $data = array();
            $data['is_self_confirm'] = 1;
            $data['dealer_pay_status'] = 1;
            $data['dealer_pay_mode'] = 1;
            $res = $order ->updateOrder($data);
            $map = array();
            $payer_info = array();
            $payer_info['settlement_time'] = date('Y-m-d H:i:s');
            $map['order_id'] = array('eq',$order_id);
            $res1 = M('proceeds_log')->where($map)->save($payer_info);
            if ($res && $res1) {
                M()->commit();
                $this->api_200($res);
            } else {
                M()->rollback();
                AuctionException::make_throw('100066');
            }
        }
    }
    /**
     * 完成结算 客户端v1.5.1版本用接口
     * @author niuzhixin 16-10-17
     */
    public function complete_balance_v151(){
        $order_id = I('post.order_id',0);
        $time = date('Y-m-d H:i:s');
        if ($order_id < 1) {
            AuctionException::make_throw('700027');
        }
        $order = new AuOrder($order_id);
        $order_info = $order->detail();
        $bl = new BuyCarList($this->dealer_id);
        $final_price = $bl->set_final_price($order_info['car_id'],$order_id,2);
        if($final_price < 0){
            AuctionException::make_throw('500024');
        }
        if($order_info['is_lock'] == 1){
            AuctionException::make_throw('700047');
        }
        if ($order_info['dealer_pay_status'] > 0 || $order_info['is_self_confirm'] == 1) {
            AuctionException::make_throw('700045');
        }
        //车商是否授权
        $dealer = new Dealer($this->dealer_id);
        $dealer_credit_info = $dealer->get_dealer_credit();
        //更改代金券使用状态
        $redis = new PhpRedis(); //记录用户修改后的代金券使用结果
        $arr = ['order_id'=>$order_id];
        $redis_key = getRedisKeyByCode('REDIS_KEY','100000',$arr);
        $coupon_ids = $redis->get($redis_key);
        //开启事务
        $res2 = true;
        M()->startTrans();
        $res3 = $bl->set_final_price($order_info['car_id'],$order_id,1);  //插入order_fee表
        if($coupon_ids != 0 && $order_info['coupon']>0 ){
            //判断状态
            $order = new AuOrder($order_id);
            $order_info = $order->detail();
            if($order_info['dealer_pay_status']!=0 || $order_info['coupon']<=0){
                AuctionException::make_throw('800014');
            }
            //数据处理
            $dealer = new Dealer($this->dealer_id);
            $data = array();
            $data['dealer_id'] = $this->dealer_id;
            $data['order_id'] = $order_id;

            $data['coupon_ids'] = explode(',',$coupon_ids);
            $res2 = $dealer->do_cost_coupon_v151($data);
        }
        if ($dealer_credit_info['is_credit'] == 1) {  //授信车商
            $redis = new PhpRedis();
            $arr = ['order_id'=>$order_id];
            $redis_key = getRedisKeyByCode('REDIS_KEY','100019',$arr);
            $res = $redis->set($redis_key,1);
            $map = array();
            $payer_info = array();
            $payer_info['settlement_time'] = $time;
            $map['order_id'] = array('eq',$order_id);
            $res1 = M('proceeds_log')->where($map)->save($payer_info);
            if ($res && $res1 && $res2 && $res3) {
                M()->commit();
                $arr = ['order_id'=>$order_id];
                $redis_key_coupon = getRedisKeyByCode('REDIS_KEY','100000',$arr);
                $confirm_key = getRedisKeyByCode('REDIS_KEY','100001',$arr);
                $redis->del($redis_key_coupon);
                $redis->del($confirm_key);
                /**
                 * 修改奖券状态 user_state ->1
                 */
                $Raffle = new Raffle();
                $Raffle->card_change_state($order_id,1);
                $this->api_200($res);
            }else {
                M()->rollback();
                AuctionException::make_throw('100066');
            }
        }else{
            $data = array();
            $data['is_self_confirm'] = 1;
            $data['dealer_pay_status'] = 1;
            $data['dealer_pay_mode'] = 1;
            $res = $order ->updateOrder($data);
            $map = array();
            $payer_info = array();
            $payer_info['settlement_time'] = $time;
            $map['order_id'] = array('eq',$order_id);
            $res1 = M('proceeds_log')->where($map)->save($payer_info);
            //添加收款单
            $info = array();
            $info['collection_no'] = genBillsNo("SK", 01);
            $info['status'] = 0; //状态都是未收
            $info['payment_type'] = 1; //车款应收 非授信车商
            $info['payment_method'] = 1; // 统一写成现金
            //拍单基本信息
            $o = new AuOrder($order_id);
            $order_info = $o->detail();
            $car = new Car($order_info['car_id']);
            $info['branch_id'] = $car->get_branch_id();
            $info['amount'] = $bl->set_final_price($order_info['car_id'],$order_id,2);
            $info['create_time'] = $time;
            $res4 = $o->set_collection($info);
            //插入`order_collections拍单和收款信息关联表
            $oc = array();
            $oc['order_id'] = $order_id;
            $oc['payment_type'] = 1;
            $oc['collection_id'] = $res4;
            $oc['createtime'] = $time;
            $res5 = $bl->set_order_collections($oc);
            if ($res !== false  && $res1 !== false  && $res2 !== false && $res3 !== false && $res4 !== false  && $res5 !== false ){
                M()->commit();
                $arr = ['order_id'=>$order_id];
                $redis_key_coupon = getRedisKeyByCode('REDIS_KEY','100000',$arr);
                $confirm_key = getRedisKeyByCode('REDIS_KEY','100001',$arr);
                $redis->del($redis_key_coupon);
                $redis->del($confirm_key);
                /**
                 * 修改奖券状态 user_state ->1
                 */
                $Raffle = new Raffle();
                $Raffle->card_change_state($order_id,1);
                $this->api_200($res);
            } else {
                M()->rollback();
                AuctionException::make_throw('100066');
            }
        }
    }
    /**
     * 买到的列表 客户端v1.2.0版本用接口
     * @author luhao 16-07-21
     */
    public function bought_list_v120($st=0)
    {
        $page = I('post.page/d', 1);
        $page_size = I('post.page_size/d', 20);
        $dealer_id = I('post.dealer_id/d', 0);
        $status = I('post.type/d', $st);
        // var_dump($status);
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        if ($status < 0) {
            AuctionException::make_throw('1000002');
        }
        $bl = new BuyCarList($dealer_id);
        //1:待确认、2:待付款、3:已付款、4:交易成功、5:交易失败 (旧）
        //1:待确认、2:成交待回车、3:待验车、4:待付款、5:已付款、6:交易成功、7:交易失败
        if(I('post.type/d')){
            switch(I('post.type/d')){
                case '2':$status=4;break;
                case '3':$status=5;break;
                case '4':$status=6;break;
                case '5':$status=7;break;
            }
        }

        $std_arr = [0=>"全部",1 => "待确认", 2 => "成交待回车", 3 => "待验车", 4 => "待付款", 5 => "已付款", 6 => "交易成功", 7 => "交易失败"];
        if (!array_key_exists($status, $std_arr)) {
            AuctionException::make_throw('500014');
        }
        $params = array('status' => $status);
        $result = $bl->getList($page, $page_size, $params);
        $list = empty($result['list']) ? array() : $result['list'];
        $total = empty($result['total']) ? 0 : $result['total'];
        $bought_list = array();
        foreach ($list as $k => $val) {
            $bought_list[$k]['order_id'] = $val['order_id'];

            $img = Car::get_pic_by_key($val['car_id'], "p_left_front45");//左前45°图片
            $bought_list[$k]['img'] = $img['pic_url'];

            $bought_list[$k]['composite_level'] = $val['composite_state'].$val['accident_level'];
            $bought_list[$k]['car_name'] = $val['model'];

            $transfer_limit = C('TRANSFER_LIMIT.' . $val['transfer_limit']);
            $bought_list[$k]['desc'] = $val['order_no'].'/'.$transfer_limit.'/上门自提' ;
            $bought_list[$k]['trade_time'] = date('Y-m-d H:i',strtotime($val['bidding_end_time']));
            $bought_list[$k]['state_name'] = $val['status_name'];
            $bought_list[$k]['should_pay'] = "应付总款：".$val['total_money']."元";
            $bought_list[$k]['button_info'] = $bl->get_raffle_botton($val['order_id']);
        }
        $data = array(
            'currentpage' => $page,
            'pagesize' => $page_size,
            'maxcount' => $total,
            'maxpage' => ceil($total / $page_size),
            'list' => $bought_list
        );
        $this->api_200($data);
    }
    /**
     * 买到的列表 客户端v1.6.2版本用接口
     * @author luhao 16-07-21
     */
    public function bought_list_v162($st=0)
    {
        $page = I('post.page/d', 1);
        $page_size = I('post.page_size/d', 20);
        $dealer_id = I('post.dealer_id/d', 0);
        $status = I('post.type/d', $st);
        if ($dealer_id < 1) {
            AuctionException::make_throw('500001');
        }
        if ($status < 0) {
            AuctionException::make_throw('1000002');
        }

        $bl = new BuyCarList($dealer_id);
        //1:待确认、2:待付款、3:已付款、4:交易成功、5:交易失败 (旧）
        //1:待确认、2:成交待回车、3:待验车、4:待付款、5:待过户、6:交易成功、7:交易失败

        $std_arr = [0=>"全部",1 => "待确认", 2 => "成交待回车", 3 => "待验车", 4 => "待付款", 5 => "待过户", 6 => "交易成功", 7 => "交易失败"];
        if (!array_key_exists($status, $std_arr)) {
            AuctionException::make_throw('500014');
        }
        $params = array('status' => $status);
        $result = $bl->getList($page, $page_size, $params);
        $list = empty($result['list']) ? array() : $result['list'];
        $total = empty($result['total']) ? 0 : $result['total'];
        $bought_list = array();
        foreach ($list as $k => $val) {
            $bought_list[$k]['order_id'] = $val['order_id'];

            $img = Car::get_pic_by_key($val['car_id'], "p_left_front45");//左前45°图片
            $bought_list[$k]['img'] = $img['pic_url'];

            $bought_list[$k]['composite_level'] = $val['composite_state'].$val['accident_level'];
            $bought_list[$k]['car_name'] = $val['model'];

            $transfer_limit = C('TRANSFER_LIMIT.' . $val['transfer_limit']);
            $bought_list[$k]['desc'] = $val['order_no'].'/'.$transfer_limit.'/上门自提' ;
            $bought_list[$k]['trade_time'] = date('Y-m-d H:i',strtotime($val['bidding_end_time']));
            $bought_list[$k]['state_name'] = $val['status_name'];
            $bought_list[$k]['state_type'] = $val['status_type'];
            $bought_list[$k]['should_pay'] = "应付总款：".$val['total_money']."元";
            $bought_list[$k]['dispute'] = $val['dispute'];
            $bought_list[$k]['button_info'] = $bl->get_raffle_botton($val['order_id']);
        }
        $data = array(
            'currentpage' => $page,
            'pagesize' => $page_size,
            'maxcount' => $total,
            'maxpage' => ceil($total / $page_size),
            'list' => $bought_list
        );
        $this->api_200($data);
    }
    /**
     * 待回车列表 客户端v1.2.0版本用接口
     * @author luhao 16-07-21
     */
    public function return_list_v120(){
        $this->bought_list_v120(2);
    }
    /**
     * 待回车列表 客户端v1.6.2版本用接口
     * @author luhao 16-07-21
     */
    public function return_list_v162(){
        $this->bought_list_v162(2);
    }


    /**
     * 待验车列表 客户端v1.2.0版本用接口
     * @author luhao 16-07-21
     */
    public function wait_check_list_v120(){
        $this->bought_list_v120(3);
    }
    /**
     * 待验车列表 客户端v1.6.2版本用接口
     * @author luhao 16-07-21
     */
    public function wait_check_list_v162(){
        $this->bought_list_v162(3);
    }


    /**
     * 首付款确认 客户端v1.3.0版本用接口
     * @author luhao 16-08-29
     */
    public function first_pay_confirm(){
        $xm_list_code = I('post.xm_list_code');//贷款申请编号
        $product_id = C('PROD_CAR_OLD_CLCW.0');//产品ID
        $order_id = I('post.order_id');//流水编号
        
        $result = $this->get_transaction_limit($order_id);
        $loan_log = AuOrder::get_loan_log($xm_list_code);
        $data = array();
        $o = new AuOrder($order_id);
        $order_info = $o->detail();
        $data['xm_list_code'] = $xm_list_code ;
        $data['first_pay_capi'] = $loan_log['first_pay_money']*100;
        $data['product_id']   = $product_id;
        $lowest_ratio = 1-$result['data']['bal_rate'];
        // if ($lowest_ratio>0) {
        //     $data['lowest_ratio'] = $lowest_ratio;
        // }
        $data['lowest_ratio'] = (string)$lowest_ratio;
        $data['org_book_no']  = $order_info['order_no'];
        $ximu = new XimuApi();
        $res = $ximu->_get('ORDER','confirmfirstpay',$data);
        var_dump($res);
    }

    /**
     * 收款确定 客户端v1.3.0版本用接口
     * @author luhao 16-08-29
     */
    public function pay_confirm(){
        $xm_list_code = I('post.xm_list_code');//贷款申请编号
        $product_id = C('PROD_CAR_OLD_CLCW.0');//产品ID
        $order_id = I('post.order_id');//流水编号
        $loan_log = AuOrder::get_loan_log($xm_list_code);
        $data = array();
        $o = new AuOrder($order_id);
        $order_info = $o->detail();
        $data['xm_list_code'] = $xm_list_code;
        $data['product_id']   = $product_id;
        $data['receive_amt'] = $loan_log['loan_money']*100;
        $data['ac_date'] = date('Y-m-d H:i:s');
        $data['receive_ac_no'] = C('RECEIVE_AC_NO.0');
        $data['org_book_no'] = $order_info['order_no'];
        $ximu = new XimuApi();
        $res = $ximu->_get('ORDER','confirmreceiveloans',$data);

    }

    /**
     * 3.5. 交易额度查询接口 公用
     * @author luhao 16-08-30
     */
    public function get_transaction_limit($order_id,$should_pay){
        $o = new AuOrder($order_id);
        $d = new MyAuctioned($this->dealer_id);
        $order_info = $o->detail();
        $auctioned = $d->get_by_order_id($order_id);
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();
        $cm = new CarModel();
        //查询可贷款金额
        $map = array();
        $map['product_id'] = C('PROD_CAR_OLD_CLCW.0');
        $map['out_user_code'] = $this->dealer_id;
        $map['car_deal_price'] = (string)($should_pay*100);
        $map['car_id'] = $car_info['car_no'];
        //车辆信息
        $map['car_id'] = $car_info['car_no'];//车辆编号
        $brand_name = $cm->get_model_by_id($car_info['brand_id'], 'brand');
        $series_name = $cm->get_model_by_id($car_info['series_id'], 'series');
        $model_name = $cm->get_model_by_id($car_info['model_id'], 'model');
        //车辆手续信息
        $car_procedure = $cm->get_procedure_by_car_id($order_info['car_id']);

        $map['car_mark_sign'] = $brand_name['name']?$brand_name['name']:'无';//品牌
        $map['car_serial'] = $series_name['name']?$series_name['name']:'无';//车系
        $map['car_model'] = $model_name['name']?$model_name['name']:'无';//车款
        $map['car_out_year'] = $car_info['ex_factory_date']; //出厂年月
        $map['car_no'] = C('PLATE_PREFIX')[$car_info['plate_prefix']].$car_info['plate_suffix']; //车牌号
        $map['car_chejia'] = $car_info['vin'];//车架
        $map['car_engi_no'] = $car_info['engine_no'];//发动机号
        $map['car_run_mile'] = $car_info['pointer_mileage'];//里程
        $map['car_no_date'] = $car_info['first_reg_date']." 00:00:00";//上牌日期
        $map['ns_date_to'] = $car_procedure['verify_expiry']." 00:00:00";//年审检验到期日
        $map['car_end_insurance'] = $car_procedure['com_insure_expiry']." 00:00:00";//交强险截止日期
        $map['scorerating'] = $car_info['composite_state'].$car_info['accident_level'];//评分等级
        $map['car_ep'] = C('EMISSION')[$car_info['emission']]; //环保标准
        $map['car_useage'] = C('USE_PROPERTIES')[$car_info['use_properties']];//用途
        $map['car_pailiang'] = $car_info['car_cc'];//排量
        $a = new Address();
        $city_name = $a->get_name_by_code($car_info['location_area']);
        $map['car_location'] = $city_name;//车辆所在地
        $car_guishu = $a->get_name_by_code($car_info['reg_city']);
        $map['car_guishu'] = $car_guishu;//归属地
        $map['car_isloan'] = "NO";//有无购车贷款未还 yes or no

        $ximu = new XimuApi();
        $res = $ximu->_get("CREDIT","queryalloworderbal",$map);
        return $res;
    }


        /**
    * 生成pdf
    */
    public function build_pdf($dealer_id,$loanable,$loan_period,$order_id){
        // $dealer_id = I('request.dealer_id');
        // $loanable = I('get.loanable'); //贷款金额
        // $loan_period = I('get.loan_period'); //贷款天数
        require_once ROOT_DIR.'/TCPDF/tcpdf.php'; 

        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        // set document information
        // $pdf->SetCreator(PDF_CREATOR);
        // $pdf->SetAuthor('Nicola Asuni');
        // $pdf->SetTitle('TCPDF Example 052');
        // $pdf->SetSubject('TCPDF Tutorial');
        // $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

        // set default header data
        // $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 052', PDF_HEADER_STRING);

        // // set header and footer fonts
        // $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        // set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        // set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

        // set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        // set certificate file
        $certificate = file_get_contents('server.crt');
        $certificate_key = file_get_contents('server.key');

        // set additional information
        $info = array(
            'Name' => '车来车往',
            'Location' => 'beijing',
            'Reason' => 'www.clcw.com.cn',
            'ContactInfo' => '400-6688-365',
            );

        // set document signature
        $pdf->setSignature($certificate, $certificate_key, 'clcw', '', 2, $info);

        // set font
        $pdf->SetFont('stsongstdlight ', '', 12);

        $pdf->setCellPaddings($left = "2",$top = "2",$right = "2",$bottom = "2");
        // add a page
        $pdf->AddPage();

        define('LPC_LOAN_URL','http://www.lpaiche.com');
        $text = file_get_contents(LPC_LOAN_URL.'/trade/pdf/dealer_id/'.$dealer_id.'/loanable/'.$loanable.'/loan_period/'.$loan_period.'/order_id/'.$order_id);
        $pdf->writeHTML($text, true, 0, true, 0);
        $pdf->setSignatureAppearance(180, 60, 15, 15);
        $pdf->addEmptySignatureAppearance(180, 80, 15, 15);
        $date = date("YmdH");
        if(!file_exists('/tmp/loan/'.$date)){
            @mkdir('/tmp/loan/'.$date,0777,true);
            @chmod('/tmp/loan/'.$date,0777);
        }
        $loan_info = AuOrder::get_loan_log_by_order_id($order_id);
        $xm_list_code = $loan_info['xm_list_code'];
        $file_to_save = "/tmp/loan/".$date."/applySigned_".$dealer_id."_".$xm_list_code.".pdf";
        $pdf->Output($file_to_save, 'F');
    }
    /**
    * 生成pdf的静态页面
    **/
    public function pdf(){
        $dealer_id = I('get.dealer_id');
        $loanable = I('get.loanable'); //贷款金额
        $loan_period = I('get.loan_period'); //贷款天数
        $order_id = I('get.order_id');
        $capital_loanable = cny($loanable);//大写金额
        $o = new AuOrder($order_id);
        $order_info = $o->detail();
        $array_loanable = array_reverse(str_split($loanable*100));
        $array_loanable[] = '￥';
        // var_dump($array_loanable);
        $data = array();
        $data['out_user_code'] = $dealer_id;
        $ximu = new XimuApi();
        $res = $ximu->_get('ORDER','queryContractInformation',$data);
        $financial_collection = C('FINANCIAL_COLLECTION');//财务收款数据
        $list = $res['data'];
        // $d = new Dealer($dealer_id); 
        $date = explode('-', date('Y-m-d'));
        $this->assign('date',$date);
        $this->assign('list',$list);
        $this->assign('lending_information',$lending_information);
        $this->assign('financial_collection',$financial_collection);
        $this->assign('loanable',$loanable);
        $this->assign('capital_loanable',$capital_loanable);
        $this->assign('array_loanable',$array_loanable);
        $this->assign('loan_period',$loan_period);
        $this->assign('order_info',$order_info);
        $this->display();
    }

    /**
    * 合同页
    **/
    public function pact(){
        $dealer_id = I('get.dealer_id');
        if ($dealer_id != $this->dealer_id) {
            AuctionException::make_throw('1700000');
        }
        $loanable = I('get.loanable'); //贷款金额
        $loan_period = I('get.loan_period'); //贷款天数
        $order_id = I('get.order_id');
        $capital_loanable = cny($loanable);//大写金额
        $o = new AuOrder($order_id);
        $order_info = $o->detail();
        $array_loanable = array_reverse(str_split($loanable*100));
        $array_loanable[] = '￥';
        // var_dump($array_loanable);
        $data = array();
        // $dealer_id = "20160804";
        $data['out_user_code'] = $dealer_id;
        $ximu = new XimuApi();
        $res = $ximu->_get('ORDER','queryContractInformation',$data);
        $financial_collection = C('FINANCIAL_COLLECTION');//财务收款数据
        $lending_information = C('LENDING_INFORMATION');
        $list = $res['data'];
        // $d = new Dealer($dealer_id);
        $date = explode('-', date('Y-m-d'));
        $this->assign('date',$date); 
        $this->assign('list',$list);
        $this->assign('lending_information',$lending_information);
        $this->assign('financial_collection',$financial_collection);
        $this->assign('loanable',$loanable);
        $this->assign('capital_loanable',$capital_loanable);
        $this->assign('array_loanable',$array_loanable);
        $this->assign('loan_period',$loan_period);
        $this->assign('order_info',$order_info);
        $this->display();
    }

    //更改金牌车商过户类型
    public function set_transfer_type(){
        $transfer_type = I('post.transfer_type');
        $order_id = I('post.order_id',0);
        $bl = new BuyCarList($this->dealer_id);
        $res = $bl->set_transfer_type($order_id,$transfer_type);
        if($res !== false){
            $this->api_200(null);
        }else{
            AuctionException::make_throw('500023');
        }
    }
}
